/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.suli.toHouse.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.mnt.websocket.MsgType;
import me.zhengjie.modules.mnt.websocket.SocketMsg;
import me.zhengjie.modules.mnt.websocket.WebSocketServer;
import me.zhengjie.suli.document.domain.Tray;
import me.zhengjie.suli.document.repository.TrayRepository;
import me.zhengjie.suli.inventory.domain.Inventory;
import me.zhengjie.suli.inventory.repository.InventoryRepository;
import me.zhengjie.suli.location.domain.Location;
import me.zhengjie.suli.location.repository.LocationRepository;
import me.zhengjie.suli.shusongxian.domain.AgvShusongxian;
import me.zhengjie.suli.shusongxian.repository.AgvShusongxianRepository;
import me.zhengjie.suli.tasks.domain.TaskDetail;
import me.zhengjie.suli.tasks.domain.Tasks;
import me.zhengjie.suli.tasks.repository.TaskDetailRepository;
import me.zhengjie.suli.tasks.repository.TasksRepository;
import me.zhengjie.suli.toHouse.domain.Receipt;
import me.zhengjie.suli.toHouse.domain.ReceiptDetail;
import me.zhengjie.suli.toHouse.repository.ReceiptDetailRepository;
import me.zhengjie.suli.toHouse.repository.ReceiptRepository;
import me.zhengjie.suli.toHouse.service.ReceiptService;
import me.zhengjie.suli.toHouse.service.dto.ReceiptDto;
import me.zhengjie.suli.toHouse.service.dto.ReceiptQueryCriteria;
import me.zhengjie.suli.toHouse.service.mapstruct.ReceiptMapper;
import me.zhengjie.suli.wcs.domain.AgvTaskDetail;
import me.zhengjie.suli.wcs.domain.AgvTasks;
import me.zhengjie.suli.wcs.repository.AgvTaskDetailRepository;
import me.zhengjie.suli.wcs.repository.AgvTasksRepository;
import me.zhengjie.util.AgvTaskUtil;
import me.zhengjie.util.CommonUtil;
import me.zhengjie.util.UuidUtil;
import me.zhengjie.util.Variable;
import me.zhengjie.utils.*;
import org.apache.poi.ss.formula.functions.T;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.persistence.Id;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author WYH
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2024-02-01
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class ReceiptServiceImpl implements ReceiptService {

    private final ReceiptRepository receiptRepository;
    private final ReceiptMapper receiptMapper;
    private final ReceiptDetailRepository receiptDetailRepository;
    private final CommonUtil commonUtil;
    private final InventoryRepository inventoryRepository;
    private final AgvTaskUtil agvTaskUtil;
    private final TaskDetailRepository taskDetailRepository;
    private final AgvTasksRepository agvTasksRepository;
    private final TasksRepository tasksRepository;
    private final LocationRepository locationRepository;
    private final AgvTaskDetailRepository agvTaskDetailRepository;
    private final TrayRepository trayRepository;
    private final AgvShusongxianRepository agvShusongxianRepository;

    @Value("${sccs.port}")
    private String sccsPort;

    @Value("${sccs.ip}")
    private String sccsIp;

    @Value("${agv.ip}")
    private String agvIp;

    @Value("${agv.port}")
    private String agvPort;

    @Autowired
    JdbcTemplate jdbcTemplate;

    private static String number = "";

    @Override
    public Map<String, Object> queryAll(ReceiptQueryCriteria criteria, Pageable pageable) {
        Page<Receipt> page = receiptRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(receiptMapper::toDto));
    }

    @Override
    public List<ReceiptDto> queryAll(ReceiptQueryCriteria criteria) {
        return receiptMapper.toDto(receiptRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public ReceiptDto findById(String id) {
        Receipt receipt = receiptRepository.findById(id).orElseGet(Receipt::new);
        ValidationUtil.isNull(receipt.getId(), "Receipt", "id", id);
        return receiptMapper.toDto(receipt);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReceiptDto create(Receipt resources) {
        return receiptMapper.toDto(receiptRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Receipt resources) {
        Receipt receipt = receiptRepository.findById(resources.getId()).orElseGet(Receipt::new);
        ValidationUtil.isNull(receipt.getId(), "Receipt", "id", resources.getId());
        receipt.copy(resources);
        receiptRepository.save(receipt);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(id);
            receiptDetailRepository.deleteAll(receiptDetailList);
            receiptRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<ReceiptDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ReceiptDto receipt : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("物料名称", receipt.getElName());
            map.put("物料编号", receipt.getElNo());
            map.put("数量", receipt.getPkQty());
            map.put("批次", receipt.getLotNo());
            map.put("供应商代码", receipt.getSuNo());
            map.put("供应商名称", receipt.getSuName());
            map.put("单位", receipt.getElUnit());
            map.put("VMI标识", receipt.getVmiCode());
            map.put("移动类型", receipt.getMtBwart());
            map.put("仓库", receipt.getMtArea());
            map.put("采购单号", receipt.getChNo());
            map.put("单据编号", receipt.getMtList());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public String pushSccs(String param) {
        return null;
    }

    /**
     * 归总相同物料为一个主表，每箱为子表 Allen Gao 2024-02-20
     */
    @Transactional(rollbackFor = Exception.class)
    public String procureReceipt(String param) {
        List<JSONObject> jsonObjects = JSON.parseArray(param, JSONObject.class);
        if (null != jsonObjects && jsonObjects.size() != 0) {
            List<Receipt> receiptList = new ArrayList<>();
            /** 查重 */
            String mtList = jsonObjects.get(0).getString("mt_list"); // 采购入库单号
            List<Receipt> receiptExist = receiptRepository.getReceiptsByMtList(mtList);
            if (receiptExist.size() > 0) {
                return "duplicate"; // 重复的入库单
            }

            for (JSONObject jsonObject : jsonObjects) {
                int flag = 0;
                /** step 1: 判断当前物料有没有主表 */
                if (receiptList.size() > 0) { // 如果receiptList有值
                    for (Receipt receipt : receiptList) {
                        if (receipt.getElNo().equals(jsonObject.getString("el_no")) && receipt.getLotNo().equals(jsonObject.getString("lot_no")) && receipt.getSuNo().equals(jsonObject.getString("su_no"))) {  // 如果又相同的物料的Receipt主表，直接生成ReceiptDetail
                            ReceiptDetail receiptDetail = new ReceiptDetail();
                            receiptDetail.setReceiptId(receipt.getId());
                            receiptDetail.setId(IdUtil.simpleUUID());
                            receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                            receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                            receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                            receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                            receiptDetail.setStatus(1); // 1--未完成入库
                            receiptDetailRepository.save(receiptDetail);
                            flag = 1;   // 找到相同的主表了。
                            break;
                        }
                    }
                    if (flag == 0) { // 没有Receipt主表
                        Receipt receipts = new Receipt();
                        receipts.setId(IdUtil.simpleUUID());
                        receipts.setReceiptCode(UuidUtil.genCode());   // WMS单号
                        receipts.setMtList(String.valueOf(jsonObject.get("mt_list")));   // 入库单号
                        receipts.setChNo(jsonObject.getString("ch_no"));   // 采购订单号
                        receipts.setChSeq(jsonObject.getString("ch_seq")); // 项目号
                        receipts.setSuNo(jsonObject.getString("su_no"));   // 供应商代码
                        receipts.setStatus("0");    // 单据状态
                        receipts.setSuName(jsonObject.getString("su_name"));
                        receipts.setElNo(String.valueOf(jsonObject.get("el_no")));  // 物料编号
                        receipts.setElName(String.valueOf(jsonObject.get("el_name")));  // 物料名称
                        receipts.setMtQty(jsonObject.getBigDecimal("mt_qty"));  // 入库数量
                        receipts.setElUnit(String.valueOf(jsonObject.get("el_unit")));  // 单位
                        receipts.setMtArea(String.valueOf(jsonObject.get("mt_area")));  // 入库库位
                        receipts.setWaNo(String.valueOf(jsonObject.get("wa_no")));  // 工厂
                        receipts.setLotNo(String.valueOf(jsonObject.get("lot_no")));    // 批次号
                        receipts.setVmiCode(String.valueOf(jsonObject.get("vmi_code")));    // 是否VMI
                        receipts.setRtdUser(SecurityUtils.getCurrentUsername());    // 操作人员
                        receipts.setActQty(new BigDecimal(0));  // 实际入库数量
                        receiptRepository.save(receipts);
                        receiptList.add(receipts);

                        ReceiptDetail receiptDetail = new ReceiptDetail();
                        receiptDetail.setReceiptId(receipts.getId());
                        receiptDetail.setId(IdUtil.simpleUUID());
                        receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                        receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                        receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                        receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                        receiptDetail.setStatus(1); // 1--未完成入库
                        receiptDetailRepository.save(receiptDetail);

                    }
                } else { // 如果receiptList没有值，直接创建Receipt和ReceiptDetail
                    Receipt receipts = new Receipt();
                    receipts.setId(IdUtil.simpleUUID());
                    receipts.setReceiptCode(UuidUtil.genCode());   // WMS单号
                    receipts.setMtList(String.valueOf(jsonObject.get("mt_list")));   // 入库单号
                    receipts.setChNo(jsonObject.getString("ch_no"));   // 采购订单号
                    receipts.setChSeq(jsonObject.getString("ch_seq")); // 项目号
                    receipts.setSuNo(jsonObject.getString("su_no"));   // 供应商代码
                    receipts.setStatus("0");    // 单据状态'
                    receipts.setSuName(jsonObject.getString("su_name"));
                    receipts.setElNo(String.valueOf(jsonObject.get("el_no")));  // 物料编号
                    receipts.setElName(String.valueOf(jsonObject.get("el_name")));  // 物料名称
                    receipts.setMtQty(jsonObject.getBigDecimal("mt_qty"));  // 入库数量
                    receipts.setElUnit(String.valueOf(jsonObject.get("el_unit")));  // 单位
                    receipts.setMtArea(String.valueOf(jsonObject.get("mt_area")));  // 入库库位
                    receipts.setWaNo(String.valueOf(jsonObject.get("wa_no")));  // 工厂
                    receipts.setLotNo(String.valueOf(jsonObject.get("lot_no")));    // 批次号
                    receipts.setVmiCode(String.valueOf(jsonObject.get("vmi_code")));    // 是否VMI
                    receipts.setRtdUser(SecurityUtils.getCurrentUsername());    // 操作人员
                    receipts.setActQty(new BigDecimal(0));  // 实际入库数量
                    receiptRepository.save(receipts);
                    receiptList.add(receipts);

                    ReceiptDetail receiptDetail = new ReceiptDetail();
                    receiptDetail.setReceiptId(receipts.getId());
                    receiptDetail.setId(IdUtil.simpleUUID());
                    receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                    receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                    receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                    receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                    receiptDetail.setStatus(1); // 1--未完成入库
                    receiptDetailRepository.save(receiptDetail);
                }


            }
            return "success";
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    public String checkAdd(String param) {
        List<JSONObject> jsonObjects = JSON.parseArray(param, JSONObject.class);
        if (null != jsonObjects && jsonObjects.size() != 0) {
            List<Receipt> receiptList = new ArrayList<>();
            /** 查重 */
            String mtList = jsonObjects.get(0).getString("mt_list"); // 采购入库单号
            List<Receipt> receiptExist = receiptRepository.getReceiptsByMtList(mtList);
            if (receiptExist.size() > 0) {
                return "duplicate"; // 重复的入库单
            }

            for (JSONObject jsonObject : jsonObjects) {
                int flag = 0;
                /** step 1: 判断当前物料有没有主表 */
                if (receiptList.size() > 0) { // 如果receiptList有值
                    for (Receipt receipt : receiptList) {
                        if (receipt.getElNo().equals(jsonObject.getString("el_no")) && receipt.getLotNo().equals(jsonObject.getString("lot_no")) && receipt.getSuNo().equals(jsonObject.getString("su_no"))) {  // 如果又相同的物料的Receipt主表，直接生成ReceiptDetail
                            ReceiptDetail receiptDetail = new ReceiptDetail();
                            receiptDetail.setReceiptId(receipt.getId());
                            receiptDetail.setId(IdUtil.simpleUUID());
                            receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                            receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                            receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                            receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                            receiptDetail.setStatus(1); // 1--未完成入库
                            receiptDetailRepository.save(receiptDetail);
                            flag = 1;   // 找到相同的主表了。
                            break;
                        }
                    }
                    if (flag == 0) { // 没有Receipt主表
                        Receipt receipts = new Receipt();
                        receipts.setId(IdUtil.simpleUUID());
                        receipts.setReceiptCode(UuidUtil.genCode());   // WMS单号
                        receipts.setMtList(String.valueOf(jsonObject.get("mt_list")));   // 入库单号
                        receipts.setChNo(jsonObject.getString("ch_no"));   // 采购订单号
                        receipts.setChSeq(jsonObject.getString("ch_seq")); // 项目号
                        receipts.setSuNo(jsonObject.getString("su_no"));   // 供应商代码
                        receipts.setStatus("0");    // 单据状态
                        receipts.setSuName(jsonObject.getString("su_name"));
                        receipts.setMtBwart("盘点差异入库");
                        receipts.setElNo(String.valueOf(jsonObject.get("el_no")));  // 物料编号
                        receipts.setElName(String.valueOf(jsonObject.get("el_name")));  // 物料名称
                        receipts.setMtQty(jsonObject.getBigDecimal("mt_qty"));  // 入库数量
                        receipts.setElUnit(String.valueOf(jsonObject.get("el_unit")));  // 单位
                        receipts.setMtArea(String.valueOf(jsonObject.get("mt_area")));  // 入库库位
                        receipts.setWaNo(String.valueOf(jsonObject.get("wa_no")));  // 工厂
                        receipts.setLotNo(String.valueOf(jsonObject.get("lot_no")));    // 批次号
                        receipts.setVmiCode(String.valueOf(jsonObject.get("vmi_code")));    // 是否VMI
                        receipts.setRtdUser(SecurityUtils.getCurrentUsername());    // 操作人员
                        receipts.setActQty(new BigDecimal(0));  // 实际入库数量
                        receiptRepository.save(receipts);
                        receiptList.add(receipts);

                        ReceiptDetail receiptDetail = new ReceiptDetail();
                        receiptDetail.setReceiptId(receipts.getId());
                        receiptDetail.setId(IdUtil.simpleUUID());
                        receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                        receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                        receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                        receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                        receiptDetail.setStatus(1); // 1--未完成入库
                        receiptDetailRepository.save(receiptDetail);

                    }
                } else { // 如果receiptList没有值，直接创建Receipt和ReceiptDetail
                    Receipt receipts = new Receipt();
                    receipts.setId(IdUtil.simpleUUID());
                    receipts.setReceiptCode(UuidUtil.genCode());   // WMS单号
                    receipts.setMtList(String.valueOf(jsonObject.get("mt_list")));   // 入库单号
                    receipts.setChNo(jsonObject.getString("ch_no"));   // 采购订单号
                    receipts.setChSeq(jsonObject.getString("ch_seq")); // 项目号
                    receipts.setSuNo(jsonObject.getString("su_no"));   // 供应商代码
                    receipts.setStatus("0");    // 单据状态'
                    receipts.setSuName(jsonObject.getString("su_name"));
                    receipts.setMtBwart("盘点差异入库");
                    receipts.setElNo(String.valueOf(jsonObject.get("el_no")));  // 物料编号
                    receipts.setElName(String.valueOf(jsonObject.get("el_name")));  // 物料名称
                    receipts.setMtQty(jsonObject.getBigDecimal("mt_qty"));  // 入库数量
                    receipts.setElUnit(String.valueOf(jsonObject.get("el_unit")));  // 单位
                    receipts.setMtArea(String.valueOf(jsonObject.get("mt_area")));  // 入库库位
                    receipts.setWaNo(String.valueOf(jsonObject.get("wa_no")));  // 工厂
                    receipts.setLotNo(String.valueOf(jsonObject.get("lot_no")));    // 批次号
                    receipts.setVmiCode(String.valueOf(jsonObject.get("vmi_code")));    // 是否VMI
                    receipts.setRtdUser(SecurityUtils.getCurrentUsername());    // 操作人员
                    receipts.setActQty(new BigDecimal(0));  // 实际入库数量
                    receiptRepository.save(receipts);
                    receiptList.add(receipts);

                    ReceiptDetail receiptDetail = new ReceiptDetail();
                    receiptDetail.setReceiptId(receipts.getId());
                    receiptDetail.setId(IdUtil.simpleUUID());
                    receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                    receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                    receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                    receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                    receiptDetail.setStatus(1); // 1--未完成入库
                    receiptDetailRepository.save(receiptDetail);
                }


            }
            return "success";
        }
        return null;
    }

    @Override
    public String customerReturn(String param) {
        commonUtil.httpPost("http://localhost:8000", null);
        return null;
    }

    /**
     * 推送入库单号给SCCS，接收入库单信息
     */
    @Override
    public int queryReceipt(String param) {
        JSONObject paramObject = JSON.parseObject(param);
        String poCode = paramObject.getString("poCode");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", poCode);

        /** 推送前端POCode */
        SocketMsg socketMsg = new SocketMsg(poCode, MsgType.INFO);
        try {
            WebSocketServer.sendInfo(socketMsg, "666");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        String resp = commonUtil.httpPost(Variable.WMSSelectListUrl, jsonObject);
        String s = StrUtil.strip(resp, "\"").replaceAll("\\\\", "");
//        String substring = resp.substring(1, resp.length() - 2);
        log.info(s);
        JSONObject respObject = JSON.parseObject(s);
        String tranFlg = respObject.getString("tran_flg");  // 消息类型 true/false
        String message = respObject.getString("message");   // 消息描述
        String remark = respObject.getString("remk");   // 单据类型
        String result = "";
        if (tranFlg.equals("false")) {
            return 0;
        }
        if (remark.equals("采购入库单")) {   //
            if (tranFlg.equals("true")) {    // IQC通过
                result = procureReceipt(message);    // 内部引用，创建入库单据
            } else { // IQC不通过
                return 0;
            }
        }else if (remark.equals("成本中心入库")) {
            result = procureCostCenterToHouse(message);
        }else if (remark.equals("免费入库")) {
            result = procureCostFreeToHouse(message);
        }else if (remark.equals("客户退货指令")) {
            result = procureCustomerBack(message);
        }else if (remark.contains("311")){
            result = roll(message);
        }else if (remark.contains("盘点")){
            result = checkAdd(message);
        } else if (remark.contains("411")) {
            result = vmiToFreeReceipt(message);
        } else if (remark.contains("412")) {
            result = freeToVmiReceipt(message);
        }
        if (result.equals("success")) {
            return 1;
        } else if (result.equals("duplicate")) {
            return 2;
        } else {
            return 0;
        }
    }

    /**
     * 收获到暂存区
     */
    @Override
    public int receiveToRCV(String param) {
        JSONObject jsonObject = JSON.parseObject(param);
        JSONArray selections = jsonObject.getJSONArray("selectionsList");
        JSONArray subSelections = jsonObject.getJSONArray("subSelectionsList");

        /** 把所有的Receipt下的ReceiptDetail找出来和选中的子表一起处理 */
        Set<ReceiptDetail> receiptDetailSet = new HashSet<>();
        for (int i = 0; i < selections.size(); i++) {
            JSONObject jsonObject1 = selections.getJSONObject(i);
            Receipt receipt = JSONObject.toJavaObject(jsonObject1, Receipt.class);
            List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt.getId());
            receiptDetailSet.addAll(receiptDetailList);
        }

        for (int i = 0; i < subSelections.size(); i++) {
            JSONObject jsonObjectReceiptDetail = subSelections.getJSONObject(i);
            ReceiptDetail receiptDetail = JSONObject.toJavaObject(jsonObjectReceiptDetail, ReceiptDetail.class);
            receiptDetailSet.add(receiptDetail);
        }

        List<ReceiptDetail> collect = receiptDetailSet.stream().filter(item -> item.getStatus() == 1).collect(Collectors.toList());
        if (null == collect || collect.size() == 0){
            return 0;
        }
        /** 处理ReceiptDetail, 为了复用AGV回调 */
        for (ReceiptDetail receiptDetail : receiptDetailSet) {
            if (receiptDetail.getStatus() != 1){
                continue;
            }
            receiptDetail.setStatus(2); // 2--入库完成
            receiptDetailRepository.save(receiptDetail);
            log.info(receiptDetail.getPkList() + ", 放箱完成, 并更改了入库单明细的状态。");

            Receipt receipt = receiptRepository.findById(receiptDetail.getReceiptId()).orElse(null);
            receipt.setActQty(receipt.getActQty().add(receiptDetail.getPkQty()));   // 处理实收数量
            if (receipt.getMtQty().compareTo(receipt.getActQty()) == 0){
                receipt.setStatus("2");
            }
            receiptRepository.save(receipt);

            /** 增加库存 */
            Inventory inventory = new Inventory();
            inventory.setId(IdUtil.simpleUUID());
            inventory.setMaterialCode(receipt.getElNo());
            inventory.setMaterialName(receipt.getElName());
            inventory.setLotCode(receipt.getLotNo());
            inventory.setLocationCode("暂存区");
            inventory.setWarehouseLocation("暂存区");
            inventory.setTrayCode("");
            inventory.setSuNo(receipt.getSuNo());
            inventory.setCreateTime(new Timestamp(new Date().getTime()));
            inventory.setElUnit(receipt.getElUnit());
            inventory.setBoxNumber(receiptDetail.getPkList());
            inventory.setAvailableQuantity(receiptDetail.getPkQty());
            inventory.setHoldQuantity(new BigDecimal(0));
            inventory.setTotal(receiptDetail.getPkQty());
            inventory.setGrade("0");
            inventory.setVmiCode(receipt.getVmiCode());
            inventory.setSuName(receipt.getSuName());
            inventory.setElMkDate(receiptDetail.getElMkDate());
            Inventory byBoxNumber = inventoryRepository.findByBoxNumber(receipt.getPkList());
            if (null != byBoxNumber){
                inventory.setIsHold(1);
            } else {
                inventory.setIsHold(0);
            }
            inventory.setWarehouseCode("立体库");
            inventory.setStartDate(new Timestamp(new Date().getTime()));
            inventory.setZoneCode(receipt.getMtArea());
            inventoryRepository.save(inventory);

            String mtBwart = receipt.getMtBwart();  // 移动类型
            /** 检查同一个入库单下所有的主表和所有的明细 */
            List<Receipt> receiptList = receiptRepository.getReceiptsByMtList(receipt.getMtList());
            int flag = 0;
            for (Receipt receipt1 : receiptList) {
                List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt1.getId());
                for (ReceiptDetail receiptDetail1 : receiptDetailList) {
                    if (receiptDetail1.getStatus() != 2) { // 如果有未完成的
                        flag = 1;
                    }
                }
            }
            if (!commonUtil.isStringNotEmpty(mtBwart)) {
                /** 采购入库 */
                /** 检查flag标志位  */
                if (flag == 0) {    // 全部完成
                    /** 更新收货单状态 */
                    for (Receipt receipt1 : receiptList) {
                        receipt1.setStatus("2");  // 2--收货完成
                        receiptRepository.save(receipt1);
                    }
                    JSONObject jsonObject1 = new JSONObject();
                    jsonObject1.put("Sjson", receipt.getMtList());
                    String url = sccsIp + ":" + sccsPort + "/RTDSXWMS/WMSImportMT03A";
                    String s = commonUtil.httpPost(url, jsonObject1);
                    String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                    log.info("推送采购入库给SCCS的返回值，" + resp);
                    JSONObject respJson = JSON.parseObject(resp);
                    String tranFlg = respJson.getString("tran_flg");
                    if (tranFlg.equals("true")) {
                        for (Receipt receipt1 : receiptList) {
                            receipt1.setIsSendSccs(1);  // 1--已推送
                            receiptRepository.save(receipt1);
                        }
                    }
                }
            } else if (mtBwart.equals("成本中心入库")) {
                /** 成本中心入库 */
                if (flag == 0) {    // 全部完成
                    /** 更新收货单状态 */
                    for (Receipt receipt1 : receiptList) {
                        receipt1.setStatus("2");  // 2--收货完成
                        receiptRepository.save(receipt1);
                    }
                    List<JSONObject> jsonArray = new ArrayList<>();
                    for (Receipt receipt1 : receiptList) {
                        List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt1.getId());
                        for (ReceiptDetail receiptDetail1 : receiptDetailList) {
                            JSONObject jsonObject1 = new JSONObject();
                            jsonObject1.put("mr_list", receipt1.getMtList());
                            jsonObject1.put("el_no", receipt1.getElNo());
                            jsonObject1.put("pk_list", receiptDetail1.getPkList());
                            jsonObject1.put("lot_no", receipt1.getLotNo());
                            jsonObject1.put("pk_qty", receiptDetail1.getPkQty());
                            jsonObject1.put("el_unit", receipt1.getElUnit());
                            jsonObject1.put("rtd_user", receipt1.getRtdUser());
                            jsonArray.add(jsonObject1);
                        }
                    }
                    log.info("成本中心入库推送给SCCS，" + jsonArray);
                    String url = sccsIp + ":" + sccsPort + "/RTDSXWMS/WMSImportMR01";
                    JSONObject jsonObjectSend = new JSONObject();
                    jsonObjectSend.put("Sjson", JSON.toJSONString(jsonArray));
                    String resp = commonUtil.httpPost(url, JSON.toJSON(jsonObjectSend));
                    log.info("成本中心入库SCCS返回，" + resp);
                    String respString = StrUtil.strip(resp, "\"").replaceAll("\\\\", "");
                    JSONObject jsonObjectResp = JSON.parseObject(respString);
                    String tranFlg = jsonObjectResp.getString("tran_flg");
                    if (tranFlg.equals("true")) {
                        for (Receipt receipt1 : receiptList) {
                            receipt1.setIsSendSccs(1);  // 1--已推送
                            receiptRepository.save(receipt1);
                        }
                    }
                }
            } else if (mtBwart.equals("免费入库")) {
                /** 免费入库 */
                if (flag == 0) {    // 全部完成
                    List<JSONObject> jsonArray = new ArrayList<>();
                    /** 更新收货单状态 */
                    for (Receipt receipt1 : receiptList) {
                        receipt1.setStatus("2");  // 2--收货完成
                        receiptRepository.save(receipt1);
                    }
                    for (Receipt receipt1 : receiptList) {
                        List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt1.getId());
                        for (ReceiptDetail receiptDetail1 : receiptDetailList) {
                            JSONObject jsonObject1 = new JSONObject();
                            jsonObject1.put("mr_list", receipt1.getMtList());   // 入库单号
                            jsonObject1.put("el_no", receipt1.getElNo());   // 物料编码
                            jsonObject1.put("pk_list", receiptDetail1.getPkList()); // 箱号
                            jsonObject1.put("lot_no", receipt1.getLotNo()); // 批次号
                            jsonObject1.put("pk_qty", receiptDetail1.getPkQty());   // 数量
                            jsonObject1.put("su_no", receipt1.getSuNo());  //   供应商代码
                            jsonArray.add(jsonObject1);
                        }
                    }
                    log.info("免费入库推送给SCCS，" + jsonArray);
                    JSONObject jsonObject1 = new JSONObject();
                    jsonObject1.put("Sjson", JSON.toJSONString(jsonArray));
                    String url = sccsIp + ":" + sccsPort + "/RTDSXWMS/WMSImportMR01";
                    String s = commonUtil.httpPost(url, jsonObject1.toJSONString());
                    String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                    log.info("免费入库SCCS返回，" + resp);
                    JSONObject jsonObjectResp = JSON.parseObject(resp);
                    String tranFlg = jsonObjectResp.getString("tran_flg");
                    if (tranFlg.equals("true")) {
                        for (Receipt receipt1 : receiptList) {
                            receipt1.setStatus("2");  // 2--收货完成
                            receipt1.setIsSendSccs(1);  // 1--已推送
                            receiptRepository.save(receipt1);
                        }
                    }
                }
            } else if (mtBwart.equals("转仓入库")) {
                /** 转仓入库 */
                if (flag == 0) {    // 全部完成
                    /** 更新收货单状态 */
                    for (Receipt receipt1 : receiptList) {
                        receipt1.setStatus("2");  // 2--收货完成
                        receiptRepository.save(receipt1);
                    }
                    List<JSONObject> jsonObjectList = new ArrayList<>();
                    for (Receipt receipt1 : receiptList) {
                        List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt1.getId());
                        for (ReceiptDetail receiptDetail1 : receiptDetailList) {
                            JSONObject jsonObject1 = new JSONObject();
                            jsonObject1.put("mr_list", receipt1.getMtList());   // 入库单号
                            jsonObject1.put("el_no", receipt1.getElNo());   // 物料编码
                            jsonObject1.put("el_name", receipt1.getElName());    // 物料名称
                            jsonObject1.put("pk_list", receiptDetail1.getPkList()); // 箱号
                            jsonObject1.put("lot_no", receipt1.getLotNo()); // 批次号
                            jsonObject1.put("pk_qty", receiptDetail1.getPkQty());   // 数量
                            jsonObject1.put("rtd_user", "admin");   // 数量
                            jsonObject1.put("vmi_code", null == receiptDetail1.getVmiCode() ? "" : receiptDetail1.getVmiCode());   // 数量
                            jsonObjectList.add(jsonObject1);
                        }
                    }
                    log.info("转仓入库推送给SCCS，" + jsonObjectList);
                    String url = sccsIp + ":" + sccsPort + "/RTDSXWMS/WMSImportMR03";
                    JSONObject jsonObjectSend = new JSONObject();
                    jsonObjectSend.put("Sjson", JSON.toJSONString(jsonObjectList));
                    String s = commonUtil.httpPost(url, JSON.toJSON(jsonObjectSend));
                    String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                    log.info("转仓入库SCCS返回，" + resp);
                    JSONObject jsonObjectResp = JSON.parseObject(resp);
                    String tranFlg = jsonObjectResp.getString("tran_flg");
                    if (tranFlg.equals("true")) {
                        for (Receipt receipt1 : receiptList) {
                            receipt1.setIsSendSccs(1);  // 1--已推送
                            receiptRepository.save(receipt1);
                        }
                    }
                }
            } else if (mtBwart.equals("客户退货")) {
                /** 客户退货 */
                if (flag == 0) {    // 全部完成
                    /** 更新收货单状态 */
                    for (Receipt receipt1 : receiptList) {
                        receipt1.setStatus("2");  // 2--收货完成
                        receiptRepository.save(receipt1);
                    }
                    List<JSONObject> jsonObjectList = new ArrayList<>();
                    for (Receipt receipt1 : receiptList) {
                        List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt1.getId());
                        for (ReceiptDetail receiptDetail1 : receiptDetailList) {
                            JSONObject jsonObject1 = new JSONObject();
                            jsonObject1.put("pd_list", receipt1.getMtList());   // 入库单号
                            jsonObject1.put("el_no", receipt1.getElNo());   // 物料编码
                            jsonObject1.put("pk_list", receiptDetail1.getPkList()); // 箱号
                            jsonObject1.put("lot_no", receipt1.getLotNo()); // 批次号
                            jsonObject1.put("pk_qty", receiptDetail1.getPkQty());   // 数量
                            jsonObject1.put("rtd_user", "admin");   // 数量
                            jsonObject1.put("vmi_code", null == receiptDetail1.getVmiCode() ? "" : receiptDetail1.getVmiCode());   // 数量
                            jsonObjectList.add(jsonObject1);
                        }
                    }
                    log.info("客户退货，推送给SCCS，" + jsonObjectList);
                    String url = sccsIp + ":" + sccsPort + "/RTDSXWMS/WMSImportPD07";
                    JSONObject jsonObjectSend = new JSONObject();
                    jsonObjectSend.put("Sjson", JSON.toJSONString(jsonObjectList));
                    String resp = commonUtil.httpPost(url, JSON.toJSON(jsonObjectSend));
                    log.info("客户退货，SCCS返回，" + resp);
                    String respString = StrUtil.strip(resp, "\"").replaceAll("\\\\", "");
                    JSONObject jsonObjectResp = JSON.parseObject(respString);
                    String tranFlg = jsonObjectResp.getString("tran_flg");
                    if (tranFlg.equals("true")) {
                        for (Receipt receipt1 : receiptList) {
                            receipt1.setIsSendSccs(1);  // 1--已推送
                            receiptRepository.save(receipt1);
                        }
                    }
                }
            }
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int zuPanConfirm(String param) {
        int x = 0;
        JSONObject jsonObject = JSON.parseObject(param);
        String trayCode = jsonObject.getString("trayCode");
        if (null == trayCode || trayCode.equals("")){
            return 6;
        }
        String pkLists = jsonObject.getString("mtList");
        String[] ptListArray = pkLists.split("\n");
        BigDecimal totalQty = new BigDecimal(0);
        /** 生成上架任务 */
        Tasks tasks = new Tasks();
        tasks.setId(IdUtil.simpleUUID());
        tasks.setTaskCode(UuidUtil.genCode());
        tasks.setTaskType(1);    // 1--入库
        tasks.setStatus(1); // 1--执行中
        tasks.setTrayCode(trayCode);
        tasks.setStartTime(new Timestamp(new Date().getTime()));

        /** 添加AGV任务 */
        AgvTasks agvTasks = new AgvTasks();
        agvTasks.setId(IdUtil.simpleUUID());
        agvTasks.setTaskGroupCode(UuidUtil.genCode());
        agvTasks.setBillNumber(tasks.getTaskCode());
        agvTasks.setTaskType("putaway");
        agvTasks.setStatus(0);
        agvTasks.setGroupPriority(0);
        agvTasksRepository.save(agvTasks);

        String toLocationCode = "";
        int flag = 0;

        /** 发送给AGV的报文 */
        JSONArray jsonArray = new JSONArray();

        for (String pkList : ptListArray) { // pkList箱号
            if (null == pkList || "".equals(pkList)){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return 2;
            }
            if (pkList.equals("S")){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return 7;
            }
            if (pkList.contains("s")){
                pkList = pkList.replaceAll("s","S");
            }
            ReceiptDetail receiptDetail = new ReceiptDetail();
            receiptDetail = receiptDetailRepository.getReceiptDetailsByPkList(pkList);
            if (null == receiptDetail){
                Inventory inventory = inventoryRepository.findByBoxNumber(pkList);
                if (null == inventory || null == inventory.getWarehouseLocation()){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return 2;
                }
            }
            Receipt receipt = new Receipt();
                receipt = receiptRepository.findById(receiptDetail.getReceiptId()).orElse(null);
                if (null != receipt && null != receipt.getMtArea()){
//                    if (!receipt.getMtArea().equals("0015") || !receipt.getMtArea().equals("0016") || !receipt.getMtArea().equals("S015") || !receipt.getMtArea().equals("S016")){
//                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                        return 17;
//                    }
                }
            if (null != receipt){
                if (receipt.getElName().equals("过载保护器")){
                    if (!trayCode.contains("B")){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return 15;
                    }
                }else{
                    if (!trayCode.contains("A")){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return 16;
                    }
                }
            }

            /** 库存查重 */
            Inventory inventoryExist = inventoryRepository.findByBoxNumber(pkList);
            Inventory inventoryExist1 = inventoryRepository.findByTrayCodeTop(trayCode);
            if (null != inventoryExist1){
                return 4;
            }
            if (null != receiptDetail){
                receiptDetail.setPkList(pkList);
                receiptDetailRepository.save(receiptDetail);
            }
            Inventory inventory = new Inventory();
            if (null != inventoryExist ) {
                if (inventoryExist.getWarehouseLocation().equals("暂存区")) {
                    /** 暂存区组盘入库 */
                    Inventory byBoxNumberAndNotLocation = inventoryRepository.findByBoxNumberAndNotLocation(inventoryExist.getBoxNumber());
                    if (null != byBoxNumberAndNotLocation){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return 4;
                    }
                    inventory = inventoryExist;
                    inventory.setBoxNumber(pkList);
                    inventory.setWarehouseLocation("");
                    inventory.setLocationCode("");
//                    inventory.setSuNo(receipt.getSuNo());
                }else{
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return 4;
                }
            } else {
                if (receiptDetail.getStatus() == 2){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return 5;
                }
                inventory.setId(IdUtil.simpleUUID());
                inventory.setMaterialCode(receipt.getElNo());
                inventory.setMaterialName(receipt.getElName());
                inventory.setLotCode(receipt.getLotNo());
                inventory.setAvailableQuantity(receiptDetail.getPkQty());
                inventory.setHoldQuantity(new BigDecimal(0));
                inventory.setTotal(receiptDetail.getPkQty());
                inventory.setGrade("0");
                inventory.setSuName(receipt.getSuName());
                inventory.setLocationCode(toLocationCode);
                inventory.setBoxNumber(pkList);
                inventory.setIsHold(0);
                inventory.setStartDate(new Timestamp(new Date().getTime()));
                inventory.setTrayCode(trayCode);
                inventory.setZoneCode(receipt.getMtArea()); // 所属库区
                inventory.setSuNo(receipt.getSuNo());   // 供应商
                inventory.setElMkDate(receiptDetail.getElMkDate());
                inventory.setElUnit(receipt.getElUnit());   // 单位
            }


            if (commonUtil.isStringNotEmpty(receipt.getVmiCode())) {
                inventory.setVmiCode(receipt.getVmiCode()); // VMI
            } else {
                inventory.setVmiCode("");
            }
            if (trayCode.contains("A")) {
                inventory.setWarehouseCode("常温库");
            } else if (trayCode.contains("B")) {
                inventory.setWarehouseCode("恒温库");
            }
            inventoryRepository.save(inventory);

            /** 防呆，判断组盘的多个收货明细是不是同一个物料 */
            if (null != tasks.getElNo() && !tasks.getElNo().equals(receipt.getElNo())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return 2;   // 不同物料不能混装
            }

            tasks.setElNo(receipt.getElNo());
            tasks.setElName(receipt.getElName());
            tasks.setElUnit(receipt.getElUnit());
            tasks.setSourceCode(receipt.getReceiptCode());

            /** 计算入库总数量 */
            if (null != receiptDetail){
                totalQty = totalQty.add(receiptDetail.getPkQty());
                tasks.setMtQty(totalQty);
            }else{
                totalQty = totalQty.add(inventory.getAvailableQuantity());
                tasks.setMtQty(totalQty);
            }


            /** 针对没有个箱号条码生成TaskDetail */
            TaskDetail taskDetail = new TaskDetail();
            if (null == receiptDetail){
                taskDetail.setId(IdUtil.simpleUUID());
                taskDetail.setPkList(inventory.getBoxNumber());    // 箱号条码
                taskDetail.setPkQty(inventory.getTotal());  // 箱号数量
                taskDetail.setWaNo(inventory.getWaNo());
                taskDetail.setLotNo(inventory.getLotCode());
                taskDetail.setVmiCode(inventory.getVmiCode());
                taskDetail.setTaskCode(UuidUtil.genCode());
                taskDetail.setSourceId("");
                taskDetail.setTaskId(tasks.getId());
                taskDetail.setSuNo(inventory.getSuNo());
                taskDetailRepository.save(taskDetail);
            }else {
                taskDetail.setId(IdUtil.simpleUUID());
                taskDetail.setPkList(receiptDetail.getPkList());    // 箱号条码
                taskDetail.setPkQty(receiptDetail.getPkQty());  // 箱号数量
                taskDetail.setWaNo(receipt.getWaNo());
                taskDetail.setLotNo(receipt.getLotNo());
                taskDetail.setVmiCode(receipt.getVmiCode());
                taskDetail.setTaskCode(UuidUtil.genCode());
                taskDetail.setSourceId(receiptDetail.getReceiptDetailCode());
                taskDetail.setTaskId(tasks.getId());
                taskDetail.setSuNo(receipt.getSuNo());
                taskDetailRepository.save(taskDetail);
            }


            /** 添加AGVTaskDetail */
            AgvTaskDetail agvTaskDetail = new AgvTaskDetail();
            agvTaskDetail.setId(IdUtil.simpleUUID());
            if (null != inventory && null != inventory.getWarehouseLocation() &&  inventory.getWarehouseLocation().equals("暂存区")) {
                agvTaskDetail.setTaskCode(taskDetail.getTaskCode());
            } else {
                agvTaskDetail.setTaskCode(taskDetail.getTaskCode());
            }
            agvTaskDetail.setFromLocationCode("暂存区");
            agvTaskDetail.setTaskPriority(0);
            agvTaskDetail.setStatus(0); // 0--未开始
            agvTaskDetail.setContainerCode(trayCode);
            agvTaskDetail.setContainerType(Variable.containerType);
            agvTaskDetail.setStorageTag("");
            agvTaskDetail.setFromLocationCode(null);
            agvTaskDetail.setToStationCode("");

            if (flag == 0) {
                /** 推荐库位 */
                List<Location> locationList = recommondLocationForMaterialCode(inventory.getMaterialName(),inventory.getMaterialCode(), trayCode);
                if (locationList.size() == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return 3; // 无空闲库位
                }
                toLocationCode = locationList.get(0).getLocationCode();
                flag = 1;

                /** 禁用库位 */
                Location location = locationList.get(0);
                location.setStatus(2);  // 2--禁用
                location.setTrayCode("");
                locationRepository.save(location);
                tasks.setLocationTo(toLocationCode);
                if (null != inventory && null != inventory.getWarehouseLocation() &&inventory.getWarehouseLocation().equals("暂存区")){
                    inventory.setIsHold(0);
                    inventory.setTrayCode(trayCode);
                    inventory.setWarehouseLocation("");
                    inventory.setLocationCode("");
                    inventoryRepository.save(inventory);
                }

            }

            agvTaskDetail.setToLocationCode(toLocationCode);  // 目标库位，必填
            agvTaskDetail.setMainId(agvTasks.getId());
            agvTaskDetail.setSourceCode(taskDetail.getTaskCode());
            agvTaskDetailRepository.save(agvTaskDetail);


            /** 发送给AGV的报文 */
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("taskCode", agvTaskDetail.getTaskCode());
            x = x + 1;
            /** 判断入库身位，如果是2身位要给高的优先级 */
            int bodyPositionIndex = toLocationCode.indexOf("_") + 1;
            String bodyPosition = toLocationCode.substring(bodyPositionIndex);
            if (bodyPosition.equals("1")) {
                jsonObject1.put("taskPriority", 0);
            }else if (bodyPosition.equals("2")) {
                jsonObject1.put("taskPriority", 2);
            }
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("containerCode", trayCode); // 料箱号
            jsonObject2.put("containerType", "CT_KUBOT_STANDARD"); // 料箱类型
            jsonObject2.put("storageTag", "");   // 留空
            jsonObject2.put("toStationCode", "CY02");
//            if (SecurityUtils.getCurrentUsername().equals("admin")){
//                jsonObject2.put("toStationCode", "CY01");
//            }else{
//                jsonObject2.put("toStationCode", "CY02");
//            }
            // 留空
//            if (SecurityUtils.getCurrentUsername().equals("admin")) {
//                jsonObject2.put("fromLocationCode", "CY01");
//            } else {
//                jsonObject2.put("fromLocationCode", "CY02");
//            }
            // 留空
//            jsonObject2.put("toStationCode", "");   // 出库的目标操作台编号，协商固定值
            jsonObject2.put("toLocationCode", toLocationCode);  // 必填

            jsonObject1.put("taskDescribe", jsonObject2);
            jsonArray.add(jsonObject1);
            if (null != receiptDetail){
                receiptDetail.setStatus(3);
                receiptDetailRepository.save(receiptDetail);
            }

        }

        tasksRepository.save(tasks);

        /** 下发给AGV */
        JSONObject jsonObject3 = new JSONObject();
        jsonObject3.put("taskType", "putaway");
        jsonObject3.put("taskGroupCode", "");
//        jsonObject3.put("groupPriority", 0);
        jsonObject3.put("tasks", jsonArray);
        log.info("发送给AGV的任务报文" + jsonObject3.toJSONString());
        String url = "http://" + agvIp + ":" + agvPort + "/task/create";
        String s = commonUtil.httpPost(url, jsonObject3.toJSONString());
        JSONObject jsonObject1 = JSON.parseObject(s);
        if (jsonObject1.getInteger("code") == 0) {
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("slotCode", "2-5");

//            if (SecurityUtils.getCurrentUsername().equals("admin")){
//                jsonObject2.put("slotCode", "1-5");
//            }else{
//                jsonObject2.put("slotCode", "2-5");
//            }
//            if (SecurityUtils.getCurrentUsername().equals("admin")) {
//                jsonObject2.put("slotCode", "1-5");
//            } else {
//                jsonObject2.put("slotCode", "1-5");
//            }
            jsonObject2.put("containerCode", trayCode);
            jsonObject2.put("direction", "100");
            String sp = commonUtil.httpPost("http://" + agvIp + ":" + agvPort + "/conveyor/moveContainer", jsonObject2.toJSONString());
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 0;
        }

//        log.info("入库任务，发送给AGV, " + jsonObject3);
//        String resp = commonUtil.httpPost(url, jsonObject3);
//
//        String url = "http://" + agvIp + ":" + agvPort + "/task/create";
//        String s = commonUtil.httpPost(url, jsonObject3.toJSONString());
//        JSONObject jsonObject1 = JSON.parseObject(s);
//        if (jsonObject1.getInteger("code") == 0) {
//            JSONObject jsonObject2 = new JSONObject();
//            if (SecurityUtils.getCurrentUsername().equals("admin")) {
//                jsonObject2.put("slotCode", "1-5");
//            } else {
//                jsonObject2.put("slotCode", "1-5");
//            }
//            jsonObject2.put("containerCode", trayCode);
//            jsonObject2.put("direction", "100");
//            String sp = commonUtil.httpPost("http://" + agvIp + ":" + agvPort + "/conveyor/moveContainer", jsonObject2.toJSONString());
//        } else {
//            return 0;
//        }
//
//        log.info("呼叫空料箱，发送给AGV, " + jsonObject3);
//        String resp = commonUtil.httpPost(url, jsonObject3);
//        log.info("呼叫空料箱，接收到AGV反馈, " + resp);

        return 1;
    }

    @Override
    public int rePushSccs(String parma) {
        List<Receipt> receiptList = receiptRepository.getReceiptsByMtList(parma);
        int flag = 0;

        for (Receipt receipt1 : receiptList) {
            List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt1.getId());
            for (ReceiptDetail receiptDetail1 : receiptDetailList) {
                if (receiptDetail1.getStatus() != 2) { // 如果有未完成的
                    flag = 1;
                    break;
                }
            }
        }
        String mtBwart = receiptList.get(0).getMtBwart();  // 移动类型

        /** 采购入库 */
        if (!commonUtil.isStringNotEmpty(mtBwart)) {
            /** 检查flag标志位  */
            if (flag == 0) {    // 全部完成
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("Sjson", parma);
                String url = sccsIp + ":" + sccsPort + "/RTDSXWMS/WMSImportMT03";
                String s = commonUtil.httpPost(url, jsonObject1);
                String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                log.info("推送采购入库给SCCS的返回值，" + resp);
                JSONObject respJson = JSON.parseObject(resp);
                String tranFlg = respJson.getString("tran_flg");
                if (tranFlg.equals("true")) {
                    for (Receipt receipt1 : receiptList) {
                        receipt1.setIsSendSccs(1);  // 1--已推送
                        receiptRepository.save(receipt1);
                    }
                    return 1;
                }
            }
        } else if (mtBwart.equals("成本中心入库")) {
            /** 成本中心入库 */
            if (flag == 0) {    // 全部完成
                List<JSONObject> jsonArray = new ArrayList<>();
                for (Receipt receipt1 : receiptList) {
                    List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt1.getId());
                    for (ReceiptDetail receiptDetail1 : receiptDetailList) {
                        JSONObject jsonObject1 = new JSONObject();
                        jsonObject1.put("mr_list", receipt1.getMtList());
                        jsonObject1.put("el_no", receipt1.getElNo());
                        jsonObject1.put("pk_list", receiptDetail1.getPkList());
                        jsonObject1.put("lot_no", receipt1.getLotNo());
                        jsonObject1.put("pk_qty", receiptDetail1.getPkQty());
                        jsonObject1.put("el_unit", receipt1.getElUnit());
                        jsonObject1.put("rtd_user", SecurityUtils.getCurrentUsername());
                        jsonArray.add(jsonObject1);
                    }
                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("Sjson", JSON.toJSONString(jsonArray));
                log.info("成本中心入库推送给SCCS，" + JSON.toJSONString(jsonArray));
                String url = sccsIp + ":" + sccsPort + "/RTDSXWMS/WMSImportMR01";
                String s = commonUtil.httpPost(url, jsonObject);
                log.info("成本中心入库SCCS返回，" + s);
                String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                JSONObject respJson = JSON.parseObject(resp);
                String tranFlg = respJson.getString("tran_flg");
                if (tranFlg.equals("true")) {
                    for (Receipt receipt1 : receiptList) {
                        receipt1.setIsSendSccs(1);  // 1--已推送
                        receiptRepository.save(receipt1);
                    }
                    return 1;
                }
            }
        } else if (mtBwart.equals("免费入库")) {
            /** 免费入库 */
            if (flag == 0) {    // 全部完成
                List<JSONObject> jsonArray = new ArrayList<>();
                for (Receipt receipt1 : receiptList) {
                    List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt1.getId());
                    for (ReceiptDetail receiptDetail1 : receiptDetailList) {
                        JSONObject jsonObject1 = new JSONObject();
                        jsonObject1.put("mr_list", receipt1.getMtList());   // 入库单号
                        jsonObject1.put("el_no", receipt1.getElNo());   // 物料编码
                        jsonObject1.put("pk_list", receiptDetail1.getPkList()); // 箱号
                        jsonObject1.put("lot_no", receipt1.getLotNo()); // 批次号
                        jsonObject1.put("pk_qty", receiptDetail1.getPkQty());   // 数量
                        jsonObject1.put("su_no", receipt1.getSuNo());  //   供应商代码
                        jsonArray.add(jsonObject1);
                    }
                }
                log.info("免费入库推送给SCCS，" + jsonArray);
                String url = sccsIp + ":" + sccsPort + "/RTDSXWMS/WMSImportMR01";
                String s = commonUtil.httpPost(url, JSON.toJSONString(jsonArray));
                String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                log.info("免费入库SCCS返回，" + resp);
                JSONObject respJson = JSON.parseObject(resp);
                String tranFlg = respJson.getString("tran_flg");
                if (tranFlg.equals("true")) {
                    for (Receipt receipt1 : receiptList) {
                        receipt1.setIsSendSccs(1);  // 1--已推送
                        receiptRepository.save(receipt1);
                    }
                    return 1;
                }
            }
        } else if (mtBwart.equals("客户退货")) {
            if (flag == 0) {
                List<JSONObject> jsonObjectList = new ArrayList<>();
                for (Receipt receipt1 : receiptList) {
                    List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt1.getId());
                    for (ReceiptDetail receiptDetail1 : receiptDetailList) {
                        JSONObject jsonObject1 = new JSONObject();
                        jsonObject1.put("pd_list", receipt1.getMtList());
                        jsonObject1.put("el_no", receipt1.getElNo());
                        jsonObject1.put("pk_list", receiptDetail1.getPkList());
                        jsonObject1.put("lot_no", receipt1.getLotNo());
                        jsonObject1.put("pk_qty", receiptDetail1.getPkQty());
                        jsonObject1.put("rtd_user", "admin");
                        jsonObject1.put("vmi_code", null == receiptDetail1.getVmiCode() ? "" : receiptDetail1.getVmiCode());   // 数量
                        jsonObjectList.add(jsonObject1);
                    }
                }
                log.info("客户退货，推送给SCCS，" + jsonObjectList);
                String url = sccsIp + ":" + sccsPort + "/RTDSXWMS/WMSImportPD07";
                JSONObject jsonObjectSend = new JSONObject();
                jsonObjectSend.put("Sjson", JSON.toJSONString(jsonObjectList));
                String resp = commonUtil.httpPost(url, JSON.toJSON(jsonObjectSend));
                log.info("客户退货，SCCS返回，" + resp);
                String respString = StrUtil.strip(resp, "\"").replaceAll("\\\\", "");
                JSONObject jsonObjectResp = JSON.parseObject(respString);
                String tranFlg = jsonObjectResp.getString("tran_flg");
                if (tranFlg.equals("true")) {
                    for (Receipt receipt1 : receiptList) {
                        receipt1.setIsSendSccs(1);  // 1--已推送
                        receiptRepository.save(receipt1);
                    }
                    return 1;
                }
            }
        } else if (mtBwart.equals("311")) {
            if (flag == 0) {
                List<JSONObject> jsonObjectList = new ArrayList<>();
                for (Receipt receipt1 : receiptList) {
                    List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt1.getId());
                    for (ReceiptDetail receiptDetail1 : receiptDetailList) {
                        JSONObject jsonObject1 = new JSONObject();
                        jsonObject1.put("mr_list", receipt1.getMtList());
                        jsonObject1.put("el_no", receipt1.getElNo());
                        jsonObject1.put("el_name", receipt1.getElName());    // 物料名称
                        jsonObject1.put("pk_list", receiptDetail1.getPkList());
                        jsonObject1.put("lot_no", receipt1.getLotNo());
                        jsonObject1.put("pk_qty", receiptDetail1.getPkQty());
                        jsonObject1.put("rtd_user", "admin");
                        jsonObject1.put("vmi_code", null == receiptDetail1.getVmiCode() ? "" : receiptDetail1.getVmiCode());
                        jsonObjectList.add(jsonObject1);
                    }
                }
                log.info("转仓入库推送给SCCS，" + jsonObjectList);
                String url = sccsIp + ":" + sccsPort + "/RTDSXWMS/WMSImportMR03";
                JSONObject jsonObjectSend = new JSONObject();
                jsonObjectSend.put("Sjson", JSON.toJSONString(jsonObjectList));
                String s = commonUtil.httpPost(url, JSON.toJSON(jsonObjectSend));
                String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                log.info("转仓入库SCCS返回，" + resp);
                JSONObject jsonObjectResp = JSON.parseObject(resp);
                String tranFlg = jsonObjectResp.getString("tran_flg");
                if (tranFlg.equals("true")) {
                    for (Receipt receipt1 : receiptList) {
                        receipt1.setIsSendSccs(1);  // 1--已推送
                        receiptRepository.save(receipt1);
                    }
                    return 1;
                }
            }
        } else if (mtBwart.equals("411")) {
            if (flag == 0) {
                List<JSONObject> jsonObjectList = new ArrayList<>();
                for (Receipt receipt1 : receiptList) {
                    List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt1.getId());
                    for (ReceiptDetail receiptDetail1 : receiptDetailList) {
                        JSONObject jsonObject1 = new JSONObject();
                        jsonObject1.put("el_no", receipt1.getElNo());
                        jsonObject1.put("mr_list", receipt1.getMtList());
                        jsonObject1.put("lot_no", receipt1.getLotNo());
                        jsonObject1.put("pk_qty", receiptDetail1.getPkQty());
                        jsonObject1.put("pk_list", receiptDetail1.getPkList());
                        jsonObject1.put("rtd_user", "admin");
                        jsonObjectList.add(jsonObject1);
                    }
                }
                log.info("自由仓转vmi推送给SCCS，" + jsonObjectList);
                String url = sccsIp + ":" + sccsPort + "/RTDSXWMS/WMSImportMR03";
                JSONObject jsonObjectSend = new JSONObject();
                jsonObjectSend.put("Sjson", JSON.toJSONString(jsonObjectList));
                String s = commonUtil.httpPost(url, JSON.toJSON(jsonObjectSend));
                String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                log.info("自由仓转vmiSCCS返回，" + resp);
                JSONObject jsonObjectResp = JSON.parseObject(resp);
                String tranFlg = jsonObjectResp.getString("tran_flg");
                if (tranFlg.equals("true")) {
                    for (Receipt receipt1 : receiptList) {
                        receipt1.setIsSendSccs(1);  // 1--已推送
                        receiptRepository.save(receipt1);
                    }
                    return 1;
                }
            }
        } else if (mtBwart.equals("412")) {
            if (flag == 0) {
                List<JSONObject> jsonObjectList = new ArrayList<>();
                for (Receipt receipt1 : receiptList) {
                    List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt1.getId());
                    for (ReceiptDetail receiptDetail1 : receiptDetailList) {
                        JSONObject jsonObject1 = new JSONObject();
                        jsonObject1.put("el_no", receipt1.getElNo());
                        jsonObject1.put("mr_list", receipt1.getMtList());
                        jsonObject1.put("lot_no", receipt1.getLotNo());
                        jsonObject1.put("pk_qty", receiptDetail1.getPkQty());
                        jsonObject1.put("pk_list", receiptDetail1.getPkList());
                        jsonObject1.put("rtd_user", "admin");
//                        jsonObject1.put("vmi_code", null == receiptDetail1.getVmiCode() ? "" : receiptDetail1.getVmiCode());
                        jsonObjectList.add(jsonObject1);
                    }
                }
                log.info("自由仓转vmi推送给SCCS，" + jsonObjectList);
                String url = sccsIp + ":" + sccsPort + "/RTDSXWMS/WMSImportMR03";
                JSONObject jsonObjectSend = new JSONObject();
                jsonObjectSend.put("Sjson", JSON.toJSONString(jsonObjectList));
                String s = commonUtil.httpPost(url, JSON.toJSON(jsonObjectSend));
                String resp = StrUtil.strip(s, "\"").replaceAll("\\\\", "");
                log.info("自由仓转vmiSCCS返回，" + resp);
                JSONObject jsonObjectResp = JSON.parseObject(resp);
                String tranFlg = jsonObjectResp.getString("tran_flg");
                if (tranFlg.equals("true")) {
                    for (Receipt receipt1 : receiptList) {
                        receipt1.setIsSendSccs(1);  // 1--已推送
                        receiptRepository.save(receipt1);
                    }
                    return 1;
                }
            }
        }
        return 0;
    }

    @Override
    public ResponseEntity<Object> emptyReturnWarehouse(String param) {
//        List<Inventory> byTrayCode = inventoryRepository.findByTrayCode(param);
//        List<Inventory> collect = byTrayCode.stream().
//                filter(item -> item.getHoldQuantity().compareTo(new BigDecimal(0)) > 0
//                        || item.getAvailableQuantity().compareTo(new BigDecimal(0)) > 0).collect(Collectors.toList());
//        if (null == collect || collect.size() == 0) {
//            inventoryRepository.deleteAll(byTrayCode);
//            String s = agvTaskUtil.receiptTaskSendToAgv(UuidUtil.genCode(), "CY02", byTrayCode.get(0).getWarehouseLocation());
//        } else {
//            collect.forEach(item -> {
//                item.setTrayCode(item.getTrayCode() + "_1");
//            });
//            String s = agvTaskUtil.receiptTaskSendToAgv(UuidUtil.genCode(), "CY02", byTrayCode.get(0).getWarehouseLocation());
//            inventoryRepository.saveAll(collect);
//        Inventory byTrayCode = inventoryRepository.findByTrayCode(param);
//        if (byTrayCode.getAvailableQuantity().compareTo(new BigDecimal(0)) == 0) {
//            inventoryRepository.delete(byTrayCode);
//            String s = agvTaskUtil.receiptTaskSendToAgv(UuidUtil.genCode(), "CY02", byTrayCode.getWarehouseLocation());
//        } else {
//            byTrayCode.setTrayCode(byTrayCode.getTrayCode() + "_1");
//            String s = agvTaskUtil.receiptTaskSendToAgv(UuidUtil.genCode(), "CY02", byTrayCode.getWarehouseLocation());
//
//        }
        //}
        return null;
    }

    @Override
    public int chuShiHua(String param) {
        synchronized (this) {
//            boolean flag = false;
//            if (!flag) {
//                return 0;
//            }
            String column = "";
            JSONObject jsonObject = JSON.parseObject(param);
            Location byTrayCode = locationRepository.findByTrayCode(jsonObject.getString("containerCode"));
            Inventory byTrayCode1 = inventoryRepository.findByTrayCodeTop(jsonObject.getString("containerCode"));
            if (null != byTrayCode || !Objects.isNull(byTrayCode)) {
                return 0;
            }
            if (jsonObject.getString("slotCode").equals("1-5")) {
                AgvShusongxian sure = agvShusongxianRepository.getSure("1-5");
                if (null == sure || sure.getNumber() == 0) {
                    return 0;
                }
                sure.setNumber(sure.getNumber() - 1);
                agvShusongxianRepository.save(sure);
                column = "2";
            } else if (jsonObject.getString("slotCode").equals("2-5")) {
                AgvShusongxian sure = agvShusongxianRepository.getSure("2-5");
                if (null == sure || sure.getNumber() == 0) {
                    return 0;
                }
                sure.setNumber(sure.getNumber() - 1);
                agvShusongxianRepository.save(sure);
                column = "1";
            }

            String kuQu = "";
            if (jsonObject.getString("containerCode").contains("A")) {
                kuQu = "%CW%";
            } else {
                kuQu = "%HW%";
            }
            List<Location> location = new ArrayList<>();
//            location = locationRepository.findByStatus("0", kuQu);
            if (jsonObject.getString("slotCode").equals("1-5")){
                location = locationRepository.findByStatusOne("0", kuQu);
            }else{
                location = locationRepository.findByStatusTwo("0", kuQu);
            }

            List<Location> collect1 = location.stream().filter(item -> null == item.getTrayCode() || "".equals(item.getTrayCode())).collect(Collectors.toList());
            List<Location> collect = collect1.stream().filter(item -> item.getLocationCode().contains("_2")).collect(Collectors.toList());
            if (null != collect && collect.size() != 0) {
                collect.get(0).setStatus(3);
                collect.get(0).setTrayCode(jsonObject.getString("containerCode"));
                locationRepository.save(collect.get(0));
                JSONObject jsonObjects = new JSONObject();
                jsonObjects.put("taskType", "putaway");
//                jsonObjects.put("groupPriority", 1);
                jsonObjects.put("taskGroupCode", UuidUtil.genCode());
                List<JSONObject> tasks = new ArrayList<>();
                JSONObject task = new JSONObject();
                task.put("taskCode", UuidUtil.genCode());
                task.put("taskPriority", 0);
                task.put("robotCode", "kubot-2");
                JSONObject jsonObject1 = new JSONObject();
//                if (jsonObject.getString("slotCode").equals("1-5")){
//                    jsonObject1.put("fromLocationCode","LT_CONVEYOR_OUTPUT:POINT:26965:11110");
//                } else if (jsonObject.getString("slotCode").equals("2-5")) {
//                    jsonObject1.put("fromLocationCode","LT_CONVEYOR_OUTPUT:POINT:26965:9160");
//                }
                jsonObject1.put("containerCode", jsonObject.getString("containerCode"));
                jsonObject1.put("storageTag", "");
                jsonObject1.put("toLocationCode", collect.get(0).getLocationCode());
                task.put("taskDescribe", jsonObject1);
                tasks.add(task);
                jsonObjects.put("tasks", tasks);
                log.info("发送给AGV" + jsonObjects.toJSONString());
                String url = "http://" + agvIp + ":" + agvPort + "/task/create";
                log.info("发送空料想入库任务，库位号：" + jsonObject1.get("containerCode"));
                String s = commonUtil.httpPost(url, jsonObjects.toJSONString());
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.put("slotCode", jsonObject.getString("slotCode"));
                jsonObject2.put("containerCode", jsonObject1.get("containerCode"));
                jsonObject2.put("direction", "100");
                String sp = commonUtil.httpPost("http://" + agvIp + ":" + agvPort + "/conveyor/moveContainer", jsonObject2.toJSONString());
            } else {
                collect1.get(0).setStatus(3);
                collect1.get(0).setTrayCode(jsonObject.getString("containerCode"));
                locationRepository.save(collect1.get(0));
                JSONObject jsonObjects = new JSONObject();
                jsonObjects.put("taskType", "putaway");
//                jsonObjects.put("groupPriority", 1);
                jsonObjects.put("taskGroupCode", UuidUtil.genCode());
                jsonObjects.put("robotCode", "kubot-2");
                List<JSONObject> tasks = new ArrayList<>();
                JSONObject task = new JSONObject();
                task.put("taskCode", UuidUtil.genCode());
                task.put("taskPriority", 0);
                JSONObject jsonObject1 = new JSONObject();
//                if (jsonObject.getString("slotCode").equals("1-5")) {
//                    jsonObject1.put("fromLocationCode", "LT_CONVEYOR_OUTPUT:POINT:26965:11110");
//                } else if (jsonObject.getString("slotCode").equals("2-5")) {
//                    jsonObject1.put("fromLocationCode", "LT_CONVEYOR_OUTPUT:POINT:26965:9160");
//                }
                jsonObject1.put("containerCode", jsonObject.getString("containerCode").replace("$", "A"));
                jsonObject1.put("storageTag", "");
                jsonObject1.put("toLocationCode", collect1.get(0).getLocationCode());
                task.put("taskDescribe", jsonObject1);
                tasks.add(task);
                jsonObjects.put("tasks", tasks);
                log.info("发送给AGV" + jsonObjects.toJSONString());
                String url = "http://" + agvIp + ":" + agvPort + "/task/create";
                log.info("发送空料想入库任务，库位号：" + jsonObject1.get("containerCode"));
                String s = commonUtil.httpPost(url, jsonObjects.toJSONString());
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.put("slotCode", jsonObject.getString("slotCode"));
                jsonObject2.put("containerCode", jsonObject1.get("containerCode"));
                jsonObject2.put("direction", "100");
                String sp = commonUtil.httpPost("http://" + agvIp + ":" + agvPort + "/conveyor/moveContainer", jsonObject2.toJSONString());
                location.get(0).setStatus(3);
                location.get(0).setTrayCode(jsonObject.getString("containerCode").replace("$", "A"));
                locationRepository.save(location.get(0));
            }

        }

//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("taskType", "carry");
//        jsonObject.put("groupPriority", 1);
//        jsonObject.put("taskGroupCode", "003");
//        List<JSONObject> tasks = new ArrayList<>();
//        JSONObject task = new JSONObject();
//        task.put("taskCode", UuidUtil.genCode());
//        task.put("taskPriority", 0);
//        JSONObject jsonObject1 = new JSONObject();
//        jsonObject1.put("fromLocationCode","CW-001-001-03_1");
//        jsonObject1.put("containerCode","A0000000906");
//        jsonObject1.put("storageTag","");
//        jsonObject1.put("toLocationCode","LT_CONVEYOR_INPUT:POINT:26965:13570");
//        task.put("taskDescribe", jsonObject1);
//        tasks.add(task);
//        jsonObject.put("tasks",tasks);
//        System.out.println(jsonObject.toJSONString());
//        String url = "http://"+agvIp + ":" + agvPort + "/task/create";
//        String s = commonUtil.httpPost(url, jsonObject.toJSONString());
//        JSONObject jsonObject2 = JSON.parseObject(s);
//        if (jsonObject2.getInteger("code") != 200){
//            return 0;
//        }
//        byStatus.setStatus(3);
//        Tray tray = new Tray();
//        tray.setId(UuidUtil.genCode());
//        tray.setTrayCode(code);
//        tray.setTrayStatus(0);
//        tray.setCreateBy("admin");
//        tray.setCreateTime(new Timestamp(new Date().getTime()));
//        tray.setLocationCode(byStatus.getLocationCode());
//        trayRepository.save(tray);
//        locationRepository.save(byStatus);
        return 1;
    }

    @Override
    public String getTrayCode() {
        UserDetails currentUser = SecurityUtils.getCurrentUser();
        JSONObject jsonObject = new JSONObject();
        if (currentUser.getUsername().equals("admin")) {
            List<String> list = new ArrayList<>();
            list.add("1");
            jsonObject.put("conveyorCodes", list);
        } else if (currentUser.getUsername().equals("song")) {
            List<String> list = new ArrayList<>();
            list.add("2");
            jsonObject.put("conveyorCodes", list);
        }else if (currentUser.getUsername().equals("abc")){
            List<String> list = new ArrayList<>();
            list.add("1");
            jsonObject.put("conveyorCodes", list);
        }
        String s = commonUtil.httpPost("http://" + agvIp + ":" + "9000" + "/equipment/conveyor/queryConveyor", jsonObject.toJSONString());
        JSONObject jsonObject1 = JSON.parseObject(s);
        if (jsonObject1.getInteger("code") != 0) {
            return "0";
        }
        JSONObject jsonObject2 = jsonObject1.getJSONObject("data");
        JSONArray conveyors = jsonObject2.getJSONArray("conveyors");
        JSONArray nodeStates = JSON.parseObject(conveyors.get(0).toString()).getJSONArray("nodeStates");
        return JSON.parseObject(nodeStates.get(1) + "").getString("containerCode");
    }

    private List<Location> recommondLocationForMaterialCode(String elName, String materialCode, String containerCode) {
        int type = 0;
        if (containerCode.contains("A")) {
            type = 1;
        } else if (containerCode.contains("B")) {
            type = 2;
        }
        List<Location> locationList = new ArrayList<>();
        List<Inventory> inventoryList = inventoryRepository.getInventoryByMaterialCodeWithLayerLessThen4(materialCode);
        if (inventoryList.size() <= 4) {    // 如果该物料在1-4层的料箱数量少于4，那么直接就会推荐到1-4层
            if (elName.equals("接线柱胶盖")){
                locationList = locationRepository.getEmptyLocationsByQtyAndTypeWithLayerLessThen4AndColumn(1, type);
            }else {
                locationList = locationRepository.getEmptyLocationsByQtyAndTypeWithLayerLessThen4(1, type);//  location.status == 0, 推荐的是空库位
            }
            if (null == locationList || locationList.size() == 0){
                locationList = locationRepository.getEmptyLocationsByQtyAndTypeOrderByLayerDesc(1, type);
            }
        } else {     // 如果在1-4层已经有该物料了, 随机给他推荐4层以上的库位
            if (elName.equals("接线柱胶盖")){
                locationList = locationRepository.getEmptyLocationsByQtyAndTypeOrderByLayerDescAndColumn(1, type);
            }else{
                locationList = locationRepository.getEmptyLocationsByQtyAndTypeOrderByLayerDesc(1, type);
            }

        }
        return locationList;
    }

    /**
     * 成本中心入库， 转化入库单
     */
    public String procureCostCenterToHouse(String param) {
        List<JSONObject> jsonObjects = JSON.parseArray(param, JSONObject.class);
        if (null != jsonObjects && jsonObjects.size() != 0) {
            List<Receipt> receiptList = new ArrayList<>();
            /** 查重 */
            String mtList = jsonObjects.get(0).getString("mr_list");    // 成本中心入库单号
            List<Receipt> receiptExist = receiptRepository.getReceiptsByMtList(mtList);
            if (receiptExist.size() > 0) {
                return "duplicate"; // 重复的入库单
            }
            for (JSONObject jsonObject : jsonObjects) {
                int flag = 0;
                /** step 1: 判断当前物料有没有主表 */
                if (receiptList.size() > 0) { // 如果receiptList有值
                    for (Receipt receipt : receiptList) {
                        if (receipt.getElNo().equals(jsonObject.getString("el_no")) && receipt.getLotNo().equals(jsonObject.getString("lot_no")) && receipt.getSuNo().equals(jsonObject.getString("su_no"))) {  // 如果又相同的物料的Receipt主表，直接生成ReceiptDetail
                            ReceiptDetail receiptDetail = new ReceiptDetail();
                            receiptDetail.setReceiptId(receipt.getId());
                            receiptDetail.setId(IdUtil.simpleUUID());
                            receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                            receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                            receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                            receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                            receiptDetail.setStatus(1); // 1--未完成入库
                            receiptDetailRepository.save(receiptDetail);
                            flag = 1;   // 找到相同的主表了。
                            break;
                        }
                    }
                    if (flag == 0) { // 没有Receipt主表
                        Receipt receipts = new Receipt();
                        receipts.setId(IdUtil.simpleUUID());
                        receipts.setReceiptCode(UuidUtil.genCode());   // WMS单号
                        receipts.setMtList(String.valueOf(jsonObject.get("mr_list")));   // 入库单号
                        receipts.setMtBwart("成本中心入库"); // 334-成本中心入库。移动类型， 涉及到修改表结构。
                        receipts.setStatus("0");    // 单据状态
                        receipts.setSuName(jsonObject.getString("su_name"));
                        receipts.setElNo(String.valueOf(jsonObject.get("el_no")));  // 物料编号
                        receipts.setElName(String.valueOf(jsonObject.get("el_name")));  // 物料名称
                        receipts.setMtQty(jsonObject.getBigDecimal("mr_qty"));  // 入库数量
                        receipts.setPkQty(jsonObject.getBigDecimal("mr_qty"));  // 入库数量
                        receipts.setElUnit(String.valueOf(jsonObject.get("el_unit")));  // 单位
                        receipts.setSuNo(jsonObject.getString("su_no"));  // 供应商代码
                        receipts.setMtArea(String.valueOf(jsonObject.get("mt_area")));  // 入库库位
                        receipts.setLotNo(String.valueOf(jsonObject.get("lot_no")));    // 批次号
                        receipts.setWaNo(String.valueOf(jsonObject.get("wa_no")));  // 工厂
                        receipts.setRtdUser(SecurityUtils.getCurrentUsername());    // 操作人员
                        receipts.setActQty(new BigDecimal(0));  // 实际入库数量
                        receipts.setVmiCode("N");
                        receipts.setIsSendSccs(0);  // 0 -- 未推送给SCCS
                        receiptRepository.save(receipts);
                        receiptList.add(receipts);

                        ReceiptDetail receiptDetail = new ReceiptDetail();
                        receiptDetail.setReceiptId(receipts.getId());
                        receiptDetail.setId(IdUtil.simpleUUID());
                        receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                        receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                        receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                        receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                        receiptDetail.setStatus(1); // 1--未完成入库
                        receiptDetailRepository.save(receiptDetail);

                    }
                } else { // 如果receiptList没有值，直接创建Receipt和ReceiptDetail
                    Receipt receipts = new Receipt();
                    receipts.setId(IdUtil.simpleUUID());
                    receipts.setReceiptCode(UuidUtil.genCode());   // WMS单号
                    receipts.setMtList(String.valueOf(jsonObject.get("mr_list")));   // 入库单号
                    receipts.setMtBwart("成本中心入库"); // 334-成本中心入库。移动类型， 涉及到修改表结构。
                    receipts.setStatus("0");    // 单据状态
                    receipts.setElNo(String.valueOf(jsonObject.get("el_no")));  // 物料编号
                    receipts.setElName(String.valueOf(jsonObject.get("el_name")));  // 物料名称
                    receipts.setMtQty(jsonObject.getBigDecimal("mr_qty"));  // 入库数量
                    receipts.setPkQty(jsonObject.getBigDecimal("mr_qty"));  // 入库数量
                    receipts.setSuNo(jsonObject.getString("su_no"));  // 供应商代码
                    receipts.setElUnit(String.valueOf(jsonObject.get("el_unit")));  // 单位
                    receipts.setMtArea(String.valueOf(jsonObject.get("mt_area")));  // 入库库位
                    receipts.setLotNo(String.valueOf(jsonObject.get("lot_no")));    // 批次号
                    receipts.setWaNo(String.valueOf(jsonObject.get("wa_no")));  // 工厂
                    receipts.setVmiCode("N");
                    receipts.setSuName(jsonObject.getString("su_name"));
                    receipts.setRtdUser(SecurityUtils.getCurrentUsername());    // 操作人员
                    receipts.setActQty(new BigDecimal(0));  // 实际入库数量
                    receipts.setIsSendSccs(0);  // 0 -- 未推送给SCCS
                    receiptRepository.save(receipts);
                    receiptList.add(receipts);

                    ReceiptDetail receiptDetail = new ReceiptDetail();
                    receiptDetail.setReceiptId(receipts.getId());
                    receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                    receiptDetail.setId(IdUtil.simpleUUID());
                    receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                    receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                    receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                    receiptDetail.setStatus(1); // 1--未完成入库
                    receiptDetailRepository.save(receiptDetail);
                }


            }
            return "success";
        }
        return null;
    }

    public int emptyBoxHuiKu(String param) {
        JSONObject jsonObject1 = JSON.parseObject(param);
        String transferLine = jsonObject1.getString("shuSongXianCode");
        int boxNumber = jsonObject1.getIntValue("boxNumber");
        String sql = "update agv_shusongxian set number = ? where id = ";
        if (transferLine.equals("输送线1")) {
            sql = sql + "1";
        } else {
            sql = sql + "2";
        }
        int result = jdbcTemplate.update(sql, boxNumber);
        return result;
    }

    @Override
    public List<ReceiptDetail> selectReceiptById(String param) {
        Receipt receipt = receiptRepository.findById(param).orElse(null);
        List<ReceiptDetail> receiptDetailsById = receiptDetailRepository.getReceiptDetailsById(receipt.getId());
        List<ReceiptDetail> collect = receiptDetailsById.stream().filter(item -> item.getStatus() == 1).collect(Collectors.toList());
        List<ReceiptDetail> collect2 = receiptDetailsById.stream().filter(item -> item.getStatus() == 2).collect(Collectors.toList());
        List<ReceiptDetail> collect3 = receiptDetailsById.stream().filter(item -> item.getStatus() == 3).collect(Collectors.toList());
        List<ReceiptDetail> receiptDetailList = new ArrayList<>();
        receiptDetailList.addAll(collect3);
        receiptDetailList.addAll(collect);
        receiptDetailList.addAll(collect2);
        return receiptDetailList;
    }

    @Override
    public List<Map<String, Object>> getReceiptDetailInfo(String param) {
        JSONObject jsonObject = JSONObject.parseObject(param);
        String pkList = jsonObject.getString("mtList"); // 箱号条码
        List<Map<String, Object>> result = new ArrayList<>();
        List<Map<String, Object>> result1 = new ArrayList<>();
        List<Map<String, Object>> result2 = new ArrayList<>();
        ReceiptDetail receiptDetail = receiptDetailRepository.getReceiptDetailsByPkList(pkList);
        if (null == receiptDetail){
            return  result;
        }
        Receipt receiptZuPan = receiptRepository.findById(receiptDetail.getReceiptId()).orElse(null);
        if ( null == receiptZuPan) {
            return  result;
        }
        List<Receipt> receiptList = receiptRepository.getReceiptsByMtList(receiptZuPan.getMtList());
        for (Receipt receipt : receiptList) {
            List<ReceiptDetail> receiptDetailList = receiptDetailRepository.getReceiptDetailsById(receipt.getId());
            for (ReceiptDetail receiptDetail1 : receiptDetailList) {
                Map<String, Object> map = new HashMap<>();
                map.put("elNo", receipt.getElNo());
                map.put("elName", receipt.getElName());
                map.put("lotCode", receiptDetail1.getLotNo());
                map.put("pkList", receiptDetail1.getPkList());
                map.put("pkQty", receiptDetail1.getPkQty());
                map.put("status", receiptDetail1.getStatus());
                if (receiptDetail1.getStatus() == 3){
                    result.add(map);
                }else if (receiptDetail1.getStatus() == 2){
                    result1.add(map);
                }else{
                    result2.add(map);
                }
            }
        }
        result.addAll(result2);
        result.addAll(result1);
        return result;
    }

    @Override
    public int sendPOCode(String param) {
        SocketMsg socketMsg = new SocketMsg(param, MsgType.INFO);
        try {
            WebSocketServer.sendInfo(socketMsg, "666");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return 1;
    }

    @Override
    public int receiveBoxNumberFromPDA(String param) {
        JSONObject jsonObject = JSON.parseObject(param);
        String boxNumber = jsonObject.getString("boxNumber");
        SocketMsg socketMsg = new SocketMsg(boxNumber, MsgType.ZUPAN);
        try {
            WebSocketServer.sendInfo(socketMsg, "666");
            return 1;
        } catch (IOException e) {
            throw new RuntimeException(e);

        }
    }

    /**
     * 免费入库， 转化入库单
     */
    private String procureCostFreeToHouse(String param) {
        List<JSONObject> jsonObjects = JSON.parseArray(param, JSONObject.class);
        if (null != jsonObjects && jsonObjects.size() != 0) {
            List<Receipt> receiptList = new ArrayList<>();
            /** 查重 */
            String mtList = jsonObjects.get(0).getString("mr_list");    // 免费入库单号
            List<Receipt> receiptExist = receiptRepository.getReceiptsByMtList(mtList);
            if (receiptExist.size() > 0) {
                return "duplicate"; // 重复的入库单
            }
            for (JSONObject jsonObject : jsonObjects) {
                int flag = 0;
                /** step 1: 判断当前物料有没有主表 */
                if (receiptList.size() > 0) { // 如果receiptList有值
                    for (Receipt receipt : receiptList) {
                        if (receipt.getElNo().equals(jsonObject.getString("el_no")) && receipt.getLotNo().equals(jsonObject.getString("lot_no")) && receipt.getSuNo().equals(jsonObject.getString("su_no"))) {  // 如果又相同的物料的Receipt主表，直接生成ReceiptDetail
                            ReceiptDetail receiptDetail = new ReceiptDetail();
                            receiptDetail.setReceiptId(receipt.getId());
                            receiptDetail.setId(IdUtil.simpleUUID());
                            receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                            receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                            receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                            receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                            receiptDetail.setStatus(1); // 1--未完成入库
                            receiptDetailRepository.save(receiptDetail);
                            flag = 1;   // 找到相同的主表了。
                            break;
                        }
                    }
                    if (flag == 0) { // 没有Receipt主表
                        Receipt receipts = new Receipt();
                        receipts.setId(IdUtil.simpleUUID());
                        receipts.setReceiptCode(UuidUtil.genCode());   // WMS单号
                        receipts.setMtList(String.valueOf(jsonObject.get("mr_list")));   // 入库单号
                        receipts.setMtBwart("免费入库"); // 551-免费入库 移动类型， 涉及到修改表结构。
                        receipts.setStatus("0");    // 单据状态
                        receipts.setSuName(jsonObject.getString("su_name"));
                        receipts.setElNo(String.valueOf(jsonObject.get("el_no")));  // 物料编号
                        receipts.setElName(String.valueOf(jsonObject.get("el_name")));  // 物料名称
                        receipts.setMtQty(jsonObject.getBigDecimal("mr_qty"));  // 入库数量
                        receipts.setPkQty(jsonObject.getBigDecimal("mr_qty"));  //入库数量
                        receipts.setElUnit(String.valueOf(jsonObject.get("el_unit")));  // 单位
                        receipts.setMtArea(String.valueOf(jsonObject.get("mt_area")));  // 入库库位
                        receipts.setLotNo(String.valueOf(jsonObject.get("lot_no")));    // 批次号
                        receipts.setSuNo(jsonObject.getString("su_no"));   // 供应商代码
                        receipts.setRtdUser(SecurityUtils.getCurrentUsername());    // 操作人员
                        receipts.setActQty(new BigDecimal(0));  // 实际入库数量
                        receipts.setIsSendSccs(0);  // 0 -- 未推送给SCCS
                        receiptRepository.save(receipts);
                        receiptList.add(receipts);

                        ReceiptDetail receiptDetail = new ReceiptDetail();
                        receiptDetail.setReceiptId(receipts.getId());
                        receiptDetail.setId(IdUtil.simpleUUID());
                        receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                        receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                        receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                        receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                        receiptDetail.setStatus(1); // 1--未完成入库
                        receiptDetailRepository.save(receiptDetail);

                    }
                } else { // 如果receiptList没有值，直接创建Receipt和ReceiptDetail
                    Receipt receipts = new Receipt();
                    receipts.setId(IdUtil.simpleUUID());
                    receipts.setReceiptCode(UuidUtil.genCode());   // WMS单号
                    receipts.setMtList(String.valueOf(jsonObject.get("mr_list")));   // 入库单号
                    receipts.setMtBwart("免费入库"); // 551-免费入库 移动类型， 涉及到修改表结构。
                    receipts.setStatus("0");    // 单据状态
                    receipts.setSuName(jsonObject.getString("su_name"));
                    receipts.setElNo(String.valueOf(jsonObject.get("el_no")));  // 物料编号
                    receipts.setElName(String.valueOf(jsonObject.get("el_name")));  // 物料名称
                    receipts.setMtQty(jsonObject.getBigDecimal("mr_qty"));  // 入库数量
                    receipts.setPkQty(jsonObject.getBigDecimal("mr_qty"));  //入库数量
                    receipts.setElUnit(String.valueOf(jsonObject.get("el_unit")));  // 单位
                    receipts.setMtArea(String.valueOf(jsonObject.get("mt_area")));  // 入库库位
                    receipts.setLotNo(String.valueOf(jsonObject.get("lot_no")));    // 批次号
                    receipts.setSuNo(jsonObject.getString("su_no"));   // 供应商代码
                    receipts.setRtdUser(SecurityUtils.getCurrentUsername());    // 操作人员
                    receipts.setActQty(new BigDecimal(0));  // 实际入库数量
                    receipts.setIsSendSccs(0);  // 0 -- 未推送给SCCS
                    receiptRepository.save(receipts);
                    receiptList.add(receipts);

                    ReceiptDetail receiptDetail = new ReceiptDetail();
                    receiptDetail.setReceiptId(receipts.getId());
                    receiptDetail.setId(IdUtil.simpleUUID());
                    receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                    receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                    receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                    receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                    receiptDetail.setStatus(1); // 1--未完成入库
                    receiptDetailRepository.save(receiptDetail);
                }


            }
            return "success";
        }
        return null;
    }

    /**
     * 转仓入库
     * @param param
     * @return
     */
    private String roll(String param){
        List<JSONObject> jsonObjects = JSON.parseArray(param, JSONObject.class);
        if (null != jsonObjects && jsonObjects.size() != 0) {
            List<Receipt> receiptList = new ArrayList<>();
            /** 查重 */
            String mtList = jsonObjects.get(0).getString("mr_list"); // 转仓单号
            List<Receipt> receiptExist = receiptRepository.getReceiptsByMtList(mtList);
            if (receiptExist.size() > 0) {
                return "duplicate"; // 重复的入库单
            }
            for (JSONObject jsonObject : jsonObjects) {
                int flag = 0;
                /** step 1: 判断当前物料有没有主表 */
                if (receiptList.size() > 0) { // 如果receiptList有值
                    for (Receipt receipt : receiptList) {
                        if (receipt.getElNo().equals(jsonObject.getString("el_no")) && receipt.getLotNo().equals(jsonObject.getString("lot_no")) && receipt.getSuNo().equals(jsonObject.getString("su_no"))) {  // 如果又相同的物料的Receipt主表，直接生成ReceiptDetail
                            ReceiptDetail receiptDetail = new ReceiptDetail();
                            receiptDetail.setReceiptId(receipt.getId());
                            receiptDetail.setId(IdUtil.simpleUUID());
                            receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                            receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                            receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                            receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                            receiptDetail.setStatus(1); // 1--未完成入库
                            receiptDetailRepository.save(receiptDetail);
                            flag = 1;   // 找到相同的主表了。
                            break;
                        }
                    }
                    if (flag == 0) { // 没有Receipt主表
                        Receipt receipts = new Receipt();
                        receipts.setId(IdUtil.simpleUUID());
                        receipts.setReceiptCode(UuidUtil.genCode());   // WMS单号
                        receipts.setMtList(String.valueOf(jsonObject.get("mr_list")));   // 入库单号（退货单）
                        receipts.setMtBwart("311"); // 客户退货 移动类型， 涉及到修改表结构。
                        receipts.setStatus("0");    // 单据状态
                        receipts.setChSeq(jsonObject.getString("ch_seq"));
                        receipts.setSuName(jsonObject.getString("su_name"));
                        receipts.setSuNo(jsonObject.getString("su_no"));
                        receipts.setMtArea(jsonObject.getString("mt_tarea"));
                        receipts.setElNo(String.valueOf(jsonObject.get("el_no")));  // 物料编号
                        receipts.setElName(String.valueOf(jsonObject.get("el_name")));  // 物料名称
                        receipts.setMtQty(jsonObject.getBigDecimal("mr_qty"));  // 入库数量
                        receipts.setPkQty(jsonObject.getBigDecimal("mr_qty"));  //入库数量
                        if (commonUtil.isStringNotEmpty(jsonObject.getString("el_unit"))) {
                            receipts.setElUnit(String.valueOf(jsonObject.get("el_unit")));  // 单位
                        }
                        receipts.setMtArea(String.valueOf(jsonObject.get("mt_tarea")));  // 入库库位
                        if (commonUtil.isStringNotEmpty(jsonObject.getString("lot_no"))) {
                            receipts.setLotNo(String.valueOf(jsonObject.get("lot_no")));  // 批次号
                        }
                            receipts.setSuNo(jsonObject.getString("su_no"));  // 供应商代码
                        if (commonUtil.isStringNotEmpty(jsonObject.getString("rtd_user"))) {
                            receipts.setRtdUser(String.valueOf(jsonObject.get("rtd_user")));  // 操作人员
                        }
                        receipts.setActQty(new BigDecimal(0));  // 实际入库数量
                        receipts.setIsSendSccs(0);  // 0 -- 未推送给SCCS
                        receiptRepository.save(receipts);
                        receiptList.add(receipts);

                        ReceiptDetail receiptDetail = new ReceiptDetail();
                        receiptDetail.setReceiptId(receipts.getId());
                        receiptDetail.setId(IdUtil.simpleUUID());
                        receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                        receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                        receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                        receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                        receiptDetail.setStatus(1); // 1--未完成入库
                        receiptDetailRepository.save(receiptDetail);

                    }
                } else { // 如果receiptList没有值，直接创建Receipt和ReceiptDetail
                    Receipt receipts = new Receipt();
                    receipts.setId(IdUtil.simpleUUID());
                    receipts.setReceiptCode(UuidUtil.genCode());   // WMS单号
                    receipts.setMtList(String.valueOf(jsonObject.get("mr_list")));   // 入库单号（退货单）
                    receipts.setMtBwart("311"); // 客户退货 移动类型， 涉及到修改表结构。
                    receipts.setStatus("0");    // 单据状态
                    receipts.setChSeq(jsonObject.getString("ch_seq"));
                    receipts.setSuName(jsonObject.getString("su_name"));
                    receipts.setSuNo(jsonObject.getString("su_no"));
                    receipts.setElNo(String.valueOf(jsonObject.get("el_no")));  // 物料编号
                    receipts.setElName(String.valueOf(jsonObject.get("el_name")));  // 物料名称
                    receipts.setMtQty(jsonObject.getBigDecimal("mr_qty"));  // 入库数量
                    receipts.setPkQty(jsonObject.getBigDecimal("mr_qty"));  //入库数量
                    if (commonUtil.isStringNotEmpty(jsonObject.getString("el_unit"))) {
                        receipts.setElUnit(String.valueOf(jsonObject.get("el_unit")));  // 单位
                    }
                    if (commonUtil.isStringNotEmpty(jsonObject.getString("mt_tarea"))) {
                        receipts.setMtArea(String.valueOf(jsonObject.get("mt_tarea")));  // 入库库位
                    }
                    if (commonUtil.isStringNotEmpty(jsonObject.getString("lot_no"))) {
                        receipts.setLotNo(String.valueOf(jsonObject.get("lot_no")));  // 批次号
                    }
                    if (commonUtil.isStringNotEmpty(jsonObject.getString("su_no"))) {
                        receipts.setSuNo(String.valueOf(jsonObject.get("su_no")));  // 供应商代码
                    }
                    if (commonUtil.isStringNotEmpty(jsonObject.getString("rtd_user"))) {
                        receipts.setRtdUser(String.valueOf(jsonObject.get("rtd_user")));  // 操作人员
                    }
                    receipts.setActQty(new BigDecimal(0));  // 实际入库数量
                    receipts.setIsSendSccs(0);  // 0 -- 未推送给SCCS
                    receiptRepository.save(receipts);
                    receiptList.add(receipts);

                    ReceiptDetail receiptDetail = new ReceiptDetail();
                    receiptDetail.setReceiptId(receipts.getId());
                    receiptDetail.setId(IdUtil.simpleUUID());
                    receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                    receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                    receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                    receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                    receiptDetail.setStatus(1); // 1--未完成入库
                    receiptDetailRepository.save(receiptDetail);
                }


            }
            return "success";
        }
        return null;
    }
    /**
     * 客户退货
     */
    private String procureCustomerBack(String param) {
        List<JSONObject> jsonObjects = JSON.parseArray(param, JSONObject.class);
        if (null != jsonObjects && jsonObjects.size() != 0) {
            List<Receipt> receiptList = new ArrayList<>();
            /** 查重 */
            String mtList = jsonObjects.get(0).getString("pd_list"); // 客户退货单号
            List<Receipt> receiptExist = receiptRepository.getReceiptsByMtList(mtList);
            if (receiptExist.size() > 0) {
                return "duplicate"; // 重复的入库单
            }
            for (JSONObject jsonObject : jsonObjects) {
                int flag = 0;
                /** step 1: 判断当前物料有没有主表 */
                if (receiptList.size() > 0) { // 如果receiptList有值
                    for (Receipt receipt : receiptList) {
                        if (receipt.getElNo().equals(jsonObject.getString("el_no")) && receipt.getLotNo().equals(jsonObject.getString("lot_no")) && receipt.getSuNo().equals(jsonObject.getString("su_no"))) {  // 如果又相同的物料的Receipt主表，直接生成ReceiptDetail
                            if (null != jsonObject.getString("el_name") && jsonObject.getString("el_name").equals("压缩机完成品")){
                                continue;
                            }
                            receipt.setMtQty(receipt.getMtQty().add(jsonObject.getBigDecimal("pk_qty")));
                            receipt.setPkQty(receipt.getPkQty().add(jsonObject.getBigDecimal("pk_qty")));
                            ReceiptDetail receiptDetail = new ReceiptDetail();
                            receiptDetail.setReceiptId(receipt.getId());
                            receiptDetail.setId(IdUtil.simpleUUID());
                            receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                            receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                            receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                            receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                            receiptDetail.setStatus(1); // 1--未完成入库
                            receiptDetailRepository.save(receiptDetail);
                            flag = 1;   // 找到相同的主表了。
                            break;
                        }
                    }
                    if (flag == 0) { // 没有Receipt主表
                        if (null != jsonObject.getString("el_name") && jsonObject.getString("el_name").equals("压缩机完成品")){
                            continue;
                        }
                        Receipt receipts = new Receipt();
                        receipts.setId(IdUtil.simpleUUID());
                        receipts.setReceiptCode(UuidUtil.genCode());   // WMS单号
                        receipts.setMtList(String.valueOf(jsonObject.get("pd_list")));   // 入库单号（退货单）
                        receipts.setMtBwart("客户退货"); // 客户退货 移动类型， 涉及到修改表结构。
                        receipts.setStatus("0");    // 单据状态
                        receipts.setSuName(jsonObject.getString("su_name"));
                        receipts.setCuNoName(jsonObject.getString("cu_name"));
                        receipts.setElNo(String.valueOf(jsonObject.get("el_no")));  // 物料编号
                        receipts.setElName(String.valueOf(jsonObject.get("el_name")));  // 物料名称
                        receipts.setMtQty(jsonObject.getBigDecimal("pk_qty"));  // 入库数量
                        receipts.setPkQty(jsonObject.getBigDecimal("pk_qty"));  //入库数量
                        if (commonUtil.isStringNotEmpty(jsonObject.getString("el_unit"))) {
                            receipts.setElUnit(String.valueOf(jsonObject.get("el_unit")));  // 单位
                        }
                        receipts.setMtArea(String.valueOf(jsonObject.get("mt_tarea")));  // 入库库位
                        if (commonUtil.isStringNotEmpty(jsonObject.getString("lot_no"))) {
                            receipts.setLotNo(String.valueOf(jsonObject.get("lot_no")));  // 批次号
                        }
                        if (commonUtil.isStringNotEmpty(jsonObject.getString("su_no"))) {
                            receipts.setSuNo(String.valueOf(jsonObject.get("su_no")));  // 供应商代码
                        }
                        if (commonUtil.isStringNotEmpty(jsonObject.getString("rtd_user"))) {
                            receipts.setRtdUser(String.valueOf(jsonObject.get("rtd_user")));  // 操作人员
                        }
                        receipts.setActQty(new BigDecimal(0));  // 实际入库数量
                        receipts.setIsSendSccs(0);  // 0 -- 未推送给SCCS
                        receiptRepository.save(receipts);
                        receiptList.add(receipts);

                        ReceiptDetail receiptDetail = new ReceiptDetail();
                        receiptDetail.setReceiptId(receipts.getId());
                        receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                        receiptDetail.setId(IdUtil.simpleUUID());
                        receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                        receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                        receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                        receiptDetail.setStatus(1); // 1--未完成入库
                        receiptDetailRepository.save(receiptDetail);

                    }
                } else { // 如果receiptList没有值，直接创建Receipt和ReceiptDetail
                    if (null != jsonObject.getString("el_name") && jsonObject.getString("el_name").equals("压缩机完成品")){
                        continue;
                    }
                    Receipt receipts = new Receipt();
                    receipts.setId(IdUtil.simpleUUID());
                    receipts.setReceiptCode(UuidUtil.genCode());   // WMS单号
                    receipts.setMtList(String.valueOf(jsonObject.get("pd_list")));   // 入库单号（退货单）
                    receipts.setMtBwart("客户退货"); // 客户退货 移动类型， 涉及到修改表结构。
                    receipts.setStatus("0");    // 单据状态
                    receipts.setSuName(jsonObject.getString("su_name"));
                    receipts.setCuNoName(jsonObject.getString("cu_name"));
                    receipts.setElNo(String.valueOf(jsonObject.get("el_no")));  // 物料编号
                    receipts.setElName(String.valueOf(jsonObject.get("el_name")));  // 物料名称
                    receipts.setMtQty(jsonObject.getBigDecimal("pk_qty"));  // 入库数量
                    receipts.setPkQty(jsonObject.getBigDecimal("pk_qty"));  //入库数量
                    if (commonUtil.isStringNotEmpty(jsonObject.getString("el_unit"))) {
                        receipts.setElUnit(String.valueOf(jsonObject.get("el_unit")));  // 单位
                    }
                    if (commonUtil.isStringNotEmpty(jsonObject.getString("mt_tarea"))) {
                        receipts.setMtArea(String.valueOf(jsonObject.get("mt_tarea")));  // 入库库位
                    }
                    if (commonUtil.isStringNotEmpty(jsonObject.getString("lot_no"))) {
                        receipts.setLotNo(String.valueOf(jsonObject.get("lot_no")));  // 批次号
                    }
                    if (commonUtil.isStringNotEmpty(jsonObject.getString("su_no"))) {
                        receipts.setSuNo(String.valueOf(jsonObject.get("su_no")));  // 供应商代码
                    }
                    if (commonUtil.isStringNotEmpty(jsonObject.getString("rtd_user"))) {
                        receipts.setRtdUser(String.valueOf(jsonObject.get("rtd_user")));  // 操作人员
                    }
                    receipts.setActQty(new BigDecimal(0));  // 实际入库数量
                    receipts.setIsSendSccs(0);  // 0 -- 未推送给SCCS
                    receiptRepository.save(receipts);
                    receiptList.add(receipts);

                    ReceiptDetail receiptDetail = new ReceiptDetail();
                    receiptDetail.setReceiptId(receipts.getId());
                    receiptDetail.setId(IdUtil.simpleUUID());
                    receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                    receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                    receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                    receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                    receiptDetail.setStatus(1); // 1--未完成入库
                    receiptDetailRepository.save(receiptDetail);
                }


            }
            return "success";
        }
        return null;
    }

    /**
     *
     * 自由转vmi入库
     * @param param
     * @return
     */
    private String freeToVmiReceipt(String param){
        List<JSONObject> jsonObjects = JSON.parseArray(param, JSONObject.class);
        if (null != jsonObjects && jsonObjects.size() != 0) {
            List<Receipt> receiptList = new ArrayList<>();
            /** 查重 */
            String mtList = jsonObjects.get(0).getString("mr_list"); // 采购入库单号
            List<Receipt> receiptExist = receiptRepository.getReceiptsByMtList(mtList);
            if (receiptExist.size() > 0) {
                return "duplicate"; // 重复的入库单
            }

            for (JSONObject jsonObject : jsonObjects) {
                int flag = 0;
                /** step 1: 判断当前物料有没有主表 */
                if (receiptList.size() > 0) { // 如果receiptList有值
                    for (Receipt receipt : receiptList) {
                        if (receipt.getElNo().equals(jsonObject.getString("el_no")) && receipt.getLotNo().equals(jsonObject.getString("lot_no")) && receipt.getSuNo().equals(jsonObject.getString("su_no"))) {  // 如果又相同的物料的Receipt主表，直接生成ReceiptDetail
                            ReceiptDetail receiptDetail = new ReceiptDetail();
                            receiptDetail.setReceiptId(receipt.getId());
                            receiptDetail.setId(IdUtil.simpleUUID());
                            LocalDate localDate = LocalDate.now();
                            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
                            String time =localDate.format(dateTimeFormatter);
                            receiptDetail.setElMkDate(time);
                            receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                            receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                            receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                            receiptDetail.setStatus(1); // 1--未完成入库
                            receiptDetailRepository.save(receiptDetail);
                            flag = 1;   // 找到相同的主表了。
                            break;
                        }
                    }
                    if (flag == 0) { // 没有Receipt主表
                        Receipt receipts = new Receipt();
                        receipts.setId(IdUtil.simpleUUID());
                        receipts.setMtBwart("412");
                        receipts.setReceiptCode(UuidUtil.genCode());   // WMS单号
                        receipts.setMtList(String.valueOf(jsonObject.get("mr_list")));   // 入库单号
                        receipts.setChNo(jsonObject.getString("ch_no"));   // 采购订单号
                        receipts.setChSeq(jsonObject.getString("ch_seq")); // 项目号
                        receipts.setSuNo(jsonObject.getString("su_no"));   // 供应商代码
                        receipts.setStatus("0");    // 单据状态
                        receipts.setSuName(jsonObject.getString("su_name"));
                        receipts.setElNo(String.valueOf(jsonObject.get("el_no")));  // 物料编号
                        receipts.setElName(String.valueOf(jsonObject.get("el_name")));  // 物料名称
                        receipts.setMtQty(jsonObject.getBigDecimal("mr_qty"));  // 入库数量
                        receipts.setElUnit(String.valueOf(jsonObject.get("el_unit")));  // 单位
                        receipts.setMtArea(String.valueOf(jsonObject.get("mt_tarea")));  // 入库库位
                        receipts.setWaNo(jsonObject.getString("wa_no"));  // 工厂
                        receipts.setLotNo(String.valueOf(jsonObject.get("lot_no")));    // 批次号
                        receipts.setVmiCode(jsonObject.getString("vmi_code"));    // 是否VMI
                        receipts.setRtdUser(SecurityUtils.getCurrentUsername());    // 操作人员
                        receipts.setActQty(new BigDecimal(0));  // 实际入库数量
                        receiptRepository.save(receipts);
                        receiptList.add(receipts);

                        ReceiptDetail receiptDetail = new ReceiptDetail();
                        receiptDetail.setReceiptId(receipts.getId());
                        receiptDetail.setId(IdUtil.simpleUUID());
                        receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                        receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                        receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                        receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                        receiptDetail.setStatus(1); // 1--未完成入库
                        receiptDetailRepository.save(receiptDetail);

                    }
                } else { // 如果receiptList没有值，直接创建Receipt和ReceiptDetail
                    Receipt receipts = new Receipt();
                    receipts.setId(IdUtil.simpleUUID());
                    receipts.setReceiptCode(UuidUtil.genCode());   // WMS单号
                    receipts.setMtList(String.valueOf(jsonObject.get("mr_list")));   // 入库单号
                    receipts.setChNo(jsonObject.getString("ch_no"));   // 采购订单号
                    receipts.setChSeq(jsonObject.getString("ch_seq")); // 项目号
                    receipts.setSuNo(jsonObject.getString("su_no"));   // 供应商代码
                    receipts.setStatus("0");    // 单据状态'
                    receipts.setMtBwart("412");
                    receipts.setSuName(jsonObject.getString("su_name"));
                    receipts.setElNo(String.valueOf(jsonObject.get("el_no")));  // 物料编号
                    receipts.setElName(String.valueOf(jsonObject.get("el_name")));  // 物料名称
                    receipts.setMtQty(jsonObject.getBigDecimal("mr_qty"));  // 入库数量
                    receipts.setElUnit(String.valueOf(jsonObject.get("el_unit")));  // 单位
                    receipts.setMtArea(String.valueOf(jsonObject.get("mt_tarea")));  // 入库库位
                    receipts.setWaNo(jsonObject.getString("wa_no"));  // 工厂
                    receipts.setLotNo(String.valueOf(jsonObject.get("lot_no")));    // 批次号
                    receipts.setVmiCode(jsonObject.getString("vmi_code"));    // 是否VMI
                    receipts.setRtdUser(SecurityUtils.getCurrentUsername());    // 操作人员
                    receipts.setActQty(new BigDecimal(0));  // 实际入库数量
                    receiptRepository.save(receipts);
                    receiptList.add(receipts);

                    ReceiptDetail receiptDetail = new ReceiptDetail();
                    receiptDetail.setReceiptId(receipts.getId());
                    receiptDetail.setId(IdUtil.simpleUUID());
                    receiptDetail.setElMkDate(jsonObject.getString("el_mkdate"));
                    receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                    receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                    receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                    receiptDetail.setStatus(1); // 1--未完成入库
                    receiptDetailRepository.save(receiptDetail);
                }


            }
            return "success";
        }
        return null;
    }

    /**
     *
     * vmi转自由入库
     * @param param
     * @return
     */
    private String vmiToFreeReceipt(String param){
        List<JSONObject> jsonObjects = JSON.parseArray(param, JSONObject.class);
        if (null != jsonObjects && jsonObjects.size() != 0) {
            List<Receipt> receiptList = new ArrayList<>();
            /** 查重 */
            String mtList = jsonObjects.get(0).getString("mr_list"); // 采购入库单号
            List<Receipt> receiptExist = receiptRepository.getReceiptsByMtList(mtList);
            if (receiptExist.size() > 0) {
                return "duplicate"; // 重复的入库单
            }

            for (JSONObject jsonObject : jsonObjects) {
                int flag = 0;
                /** step 1: 判断当前物料有没有主表 */
                if (receiptList.size() > 0) { // 如果receiptList有值
                    for (Receipt receipt : receiptList) {
                        if (receipt.getElNo().equals(jsonObject.getString("el_no")) && receipt.getLotNo().equals(jsonObject.getString("lot_no")) && receipt.getSuNo().equals(jsonObject.getString("su_no"))) {  // 如果又相同的物料的Receipt主表，直接生成ReceiptDetail
                            ReceiptDetail receiptDetail = new ReceiptDetail();
                            receiptDetail.setReceiptId(receipt.getId());
                            receiptDetail.setId(IdUtil.simpleUUID());
                            LocalDate localDate = LocalDate.now();
                            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
                            String time =localDate.format(dateTimeFormatter);
                            receiptDetail.setElMkDate(time);
                            receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                            receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                            receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                            receiptDetail.setStatus(1); // 1--未完成入库
                            receiptDetailRepository.save(receiptDetail);
                            flag = 1;   // 找到相同的主表了。
                            break;
                        }
                    }
                    if (flag == 0) { // 没有Receipt主表
                        Receipt receipts = new Receipt();
                        receipts.setId(IdUtil.simpleUUID());
                        receipts.setReceiptCode(UuidUtil.genCode());// WMS单号
                        receipts.setMtBwart("411");
                        receipts.setMtList(String.valueOf(jsonObject.get("mr_list")));   // 入库单号
                        receipts.setChNo(jsonObject.getString("ch_no"));   // 采购订单号
                        receipts.setChSeq(jsonObject.getString("ch_seq")); // 项目号
                        receipts.setSuNo(jsonObject.getString("su_no"));   // 供应商代码
                        receipts.setStatus("0");    // 单据状态
                        receipts.setSuName(jsonObject.getString("su_name"));
                        receipts.setElNo(String.valueOf(jsonObject.get("el_no")));  // 物料编号
                        receipts.setElName(String.valueOf(jsonObject.get("el_name")));  // 物料名称
                        receipts.setMtQty(jsonObject.getBigDecimal("mr_qty"));  // 入库数量
                        receipts.setElUnit(String.valueOf(jsonObject.get("el_unit")));  // 单位
                        receipts.setMtArea(String.valueOf(jsonObject.get("mt_tarea")));  // 入库库位
                        receipts.setWaNo(jsonObject.getString("wa_no"));  // 工厂
                        receipts.setLotNo(String.valueOf(jsonObject.get("lot_no")));    // 批次号
                        receipts.setVmiCode(jsonObject.getString("vmi_code"));    // 是否VMI
                        receipts.setRtdUser(SecurityUtils.getCurrentUsername());    // 操作人员
                        receipts.setActQty(new BigDecimal(0));  // 实际入库数量
                        receiptRepository.save(receipts);
                        receiptList.add(receipts);

                        ReceiptDetail receiptDetail = new ReceiptDetail();
                        receiptDetail.setReceiptId(receipts.getId());
                        receiptDetail.setId(IdUtil.simpleUUID());
                        LocalDate localDate = LocalDate.now();
                        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
                        String time =localDate.format(dateTimeFormatter);
                        receiptDetail.setElMkDate(time);
                        receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                        receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                        receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                        receiptDetail.setStatus(1); // 1--未完成入库
                        receiptDetailRepository.save(receiptDetail);

                    }
                } else { // 如果receiptList没有值，直接创建Receipt和ReceiptDetail
                    Receipt receipts = new Receipt();
                    receipts.setId(IdUtil.simpleUUID());
                    receipts.setMtBwart("411");
                    receipts.setReceiptCode(UuidUtil.genCode());   // WMS单号
                    receipts.setMtList(String.valueOf(jsonObject.get("mr_list")));   // 入库单号
                    receipts.setChNo(jsonObject.getString("ch_no"));   // 采购订单号
                    receipts.setChSeq(jsonObject.getString("ch_seq")); // 项目号
                    receipts.setSuNo(jsonObject.getString("su_no"));   // 供应商代码
                    receipts.setStatus("0");    // 单据状态'
                    receipts.setSuName(jsonObject.getString("su_name"));
                    receipts.setElNo(String.valueOf(jsonObject.get("el_no")));  // 物料编号
                    receipts.setElName(String.valueOf(jsonObject.get("el_name")));  // 物料名称
                    receipts.setMtQty(jsonObject.getBigDecimal("mr_qty"));  // 入库数量
                    receipts.setElUnit(String.valueOf(jsonObject.get("el_unit")));  // 单位
                    receipts.setMtArea(String.valueOf(jsonObject.get("mt_tarea")));  // 入库库位
                    receipts.setWaNo(jsonObject.getString("wa_no"));  // 工厂
                    receipts.setLotNo(String.valueOf(jsonObject.get("lot_no")));    // 批次号
                    receipts.setVmiCode(jsonObject.getString("vmi_code"));    // 是否VMI
                    receipts.setRtdUser(SecurityUtils.getCurrentUsername());    // 操作人员
                    receipts.setActQty(new BigDecimal(0));  // 实际入库数量
                    receiptRepository.save(receipts);
                    receiptList.add(receipts);

                    ReceiptDetail receiptDetail = new ReceiptDetail();
                    receiptDetail.setReceiptId(receipts.getId());
                    receiptDetail.setId(IdUtil.simpleUUID());
                    LocalDate localDate = LocalDate.now();
                    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
                    String time =localDate.format(dateTimeFormatter);
                    receiptDetail.setElMkDate(time);
                    receiptDetail.setReceiptDetailCode(UuidUtil.genCode());
                    receiptDetail.setPkList(String.valueOf(jsonObject.get("pk_list")));  // 箱号条码
                    receiptDetail.setPkQty(jsonObject.getBigDecimal("pk_qty"));   // 箱号数量
                    receiptDetail.setStatus(1); // 1--未完成入库
                    receiptDetailRepository.save(receiptDetail);
                }


            }
            return "success";
        }
        return null;
    }

}